callback function with underscore _.each()

早过忘川 提交于 2019-12-24 12:19:26

问题


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



来源:https://stackoverflow.com/questions/21586688/callback-function-with-underscore-each

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!