我正在完成一项任务,以复制underscore.js库的部分内容。我坚持将“each”函数实现为“唯一”函数。
我的每个功能如下:
_.each = function(collection, iterator) {
//checks to see if collection is an array or object
if (Array.isArray(collection)) {
//if array, iterates an action function on each index value
for (var i = 0; i < collection.length; i++) {
iterator(collection[i], i, collection);
}
}
//else statement takes care of an object passed as argument
else {
//for...in loop will iterate through object keys
for (var key in collection) {
iterator(collection[key], key, collection)
}
}
}
我能够在过滤函数中使用上面的每个函数,如下所示:
_.filter = function(collection, test) {
var newArray = [];
//calling _.each function to iterate through array
_.each(collection, function(value, index, list) {
//applying truth test
if (test(value, index, list)) {
newArray.push(value);
};
});
return newArray;
};
我试图在我的“独特”功能中使用每个功能,如下所示:
_.uniq = function(array) {
//two temporary arrays, one to hold unique values and one for duplicates
var unique = [];
var notUnique = [];
_.each(array, function(item, index) {
//sort array
var sortedArray = array.sort(function(a, b){return a-b});
//if value is not equal to the next value after sort, it goes to the unique array
if (sortedArray[index] !== sortedArray[index+1]) {
unique.push(sortedArray[index]);
}
//if the value matches the next value, it goes to the not unique array
else {
notUnique.push(sortedArray[index]);
}
return unique;
});
}
然而,当我在测试数组上运行它时,我收到一个未定义的输出。使用像这样的嵌套函数时,数组排序方法是否不起作用?
答案 0 :(得分:0)
您要在unique
内返回_.each
数组,所以基本上您的_.uniq
函数默认重新调整undefined
。
_.uniq = function(array) {
//two temporary arrays, one to hold unique values and one for duplicates
var unique = [];
var notUnique = [];
_.each(array, function(item, index) {
//sort array
var sortedArray = array.sort(function(a, b) {
return a - b
});
//if value is not equal to the next value after sort, it goes to the unique array
if (sortedArray[index] !== sortedArray[index + 1]) {
unique.push(sortedArray[index]);
}
//if the value matches the next value, it goes to the not unique array
else {
notUnique.push(sortedArray[index]);
}
});
return unique; // return here
}