带下划线 _.each() 的回调函数 [英] callback function with underscore _.each()

查看:46
本文介绍了带下划线 _.each() 的回调函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在另一个函数中实现一个 _.each()(我编写的),但我不断收到未定义"返回给我的信息.我正在尝试使用 _.each() 将测试函数应用于数组.我知道这是一个简单的回调语法问题,但它让我感到困惑.

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.

在此先感谢菜鸟.

这是我的功能:

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

返回未定义"

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

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; } 

这是我的 _.each():

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

推荐答案

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

修复了它

这篇关于带下划线 _.each() 的回调函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆