Javascript 带下划线的回调函数

Javascript 带下划线的回调函数,javascript,underscore.js,Javascript,Underscore.js,我试图在另一个函数中实现一个u.each()(我编写的),我不断得到“undefined”返回给我。我正在尝试使用u.each()将测试函数应用于数组。我知道这是一个简单的回调语法问题,但它让我感到困惑 提前感谢一位noob 以下是我的功能: _.filter = function(collection, test) { _.each(collection, test()); }; 这将返回“未定义” 这是我作为“集合”传递的数组: [1, 2, 3, 4, 5, 6] 这是我作为“测

我试图在另一个函数中实现一个u.each()(我编写的),我不断得到“undefined”返回给我。我正在尝试使用u.each()将测试函数应用于数组。我知道这是一个简单的回调语法问题,但它让我感到困惑

提前感谢一位noob

以下是我的功能:

_.filter = function(collection, test) {
  _.each(collection, test());
};
这将返回“未定义”

这是我作为“集合”传递的数组:

[1, 2, 3, 4, 5, 6] 
这是我作为“测试”通过的函数:

function (num) { return num % 2 !== 0; } 
这是我的u.each():

\每个=函数(集合、迭代器){
if(Object.prototype.toString.call(collection)='[Object Array]'){
对于(var i=0;i

这修复了它

try.each(collection,test);-您正在调用test函数test()您的
函数没有任何
return
语句,那么为什么您希望它返回一些东西呢?当我通过测试函数时,我传递的函数有一个return语句,而没有()我没有定义。JavaScript不是这样工作的。
return
从函数返回,而不对调用该函数的函数执行任何操作。
filter
实现也没有
return
,因此它也不会返回任何内容。如果您自己编写了函数,为什么会标记此项?
_.each = function(collection, iterator) {

    if( Object.prototype.toString.call( collection ) === '[object Array]' ) {
        for (var i=0; i<collection.length; i++){
            iterator(collection[i], i, collection);
        }
    } else if (typeof collection === 'object'){
        for (var i in collection){
            iterator(collection[i], i, collection)
        }
    } else if (typeof collection === 'int'){
        console.log('int')
    }
};
 _.filter = function(collection, test) {
  var result =[];
  _.each(collection, function(curio) { 
    if (test(curio)) 
    result.push(curio);
  });
  return result;
};