callback function with underscore _.each()

2019-08-04 01:41发布

问题:

I'm trying to implement an _.each() (that I wrote) inside another function and I keep getting "undefined" returned to me. I'm trying to use _.each() to apply a test function to an array. I know this a simple callback syntax issue, but its perplexing me.

thanks in advance from a noob.

here's my function:

_.filter = function(collection, test) {
  _.each(collection, test());
};

this returns 'undefined'

this is the array i'm passing as 'collection':

[1, 2, 3, 4, 5, 6] 

this is the function i'm passing as 'test':

function (num) { return num % 2 !== 0; } 

here's my _.each():

_.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')
    }
};

回答1:

 _.filter = function(collection, test) {
  var result =[];
  _.each(collection, function(curio) { 
    if (test(curio)) 
    result.push(curio);
  });
  return result;
};

that fixed it