// Return all elements of an array that pass a truth test.
_.filter = function(collection, test) {
var result = []; //make a result variable
//iterate over the collection array using _.each
_.each(collection, function(value) {
//if conditions for test(element) = positive
if (test(value)) {
//push element into result
result.push(value);
}
});
return result;
};
[嗨,我正在从Underscore JS库重写_.filter
和_.reject
的功能。我仍然对回调函数有些困惑,特别是当同一个函数中有太多回调函数时。我需要在这里澄清我的想法和逻辑;特别是._reject
。我正在重用_.filter
函数,并在我的_.reject
函数中使用它。
_.reject = function(collection, test) {
return _.filter(collection, function(value) {
return !test(value);
})
};
当我将function(value)作为过滤器的参数并对其进行定义时;那是用那个函数回调代替我的测试值吗?特别是在这一行中-在这种情况下,if (test(value)) {...
会被我的回调函数取代if(function(value) {return !test(value)})
此外,如果我从return
函数的_.reject
函数中省略了_.filter
命令,则此操作将被删除。我只是返回函数本身吗?抱歉-我知道这有点奇怪,因为我的代码在我所知的范围内有效,但实际上更多是尝试一些事情然后真正从逻辑上理解它。当我从我的拒绝函数中调用过滤器中的回调函数时,我只是非常困惑
//返回通过真相测试的数组的所有元素。 _.filter = function(collection,test){var result = []; //创建一个结果变量//使用_.each ...
在JavaScript中,一切都是对象,包括函数。当您编写函数表达式(如它们的调用)时,如下所示: