_.filter = function(collection, test) {
var result = [];
_.each(collection, function(value) {
if(test(value)) {
result.push(value);
}
})
return result;
};
_.reject = function(collection, test) {
var result = [];
return _.filter(collection, function(value) {
return !test(value);
})
};
我对此工作原理有些疑惑。我在同一作用域中定义了两个underscore.js函数。如果我通过一个随机数测试数组,则_.reject中的_.filter如何工作?
var isEven = function(num) { return num % 2 === 0; };
var odds = _.reject([1, 2, 3, 4, 5, 6], isEven);
expect(odds).to.eql([1, 3, 5]);
例如,我测试了我的函数,并得到了断言为真,但我不明白其工作原理
拒绝只是重复使用过滤器完成的某些逻辑。它很容易以这种方式编写:
_.reject = function(collection, test) {
var result = [];
_.each(collection, function(value) {
if(!test(value)) {
result.push(value);
}
})
return result;
};
您会注意到,筛选和拒绝之间的唯一区别是,我们是要在测试为真时还是在测试为假时保留项目。
// Creates the function reject
_.reject = function(collection, test) {
var result = [];
// Calls filter but hands in a custom callback.
// Filter iterates each item in the list, and keeps it
// if test(item) returns true (test is our custom flipResult).
// Remember that reject does the opposite, it keeps it
// if test(item) returns false (aka !true).
return _.filter(collection, function flipResult(value) {
// The user gave us a test method. We want to keep items
// that return false when passed to test.
// If we call _.filter(collection, test) we will get all
// items that return true when passed to test, but thats not what we want
// So instead of handing test in directly, we hand in our custom callback
// The custom callback calls test and flips the result.
// This means filter will keep all items that return false
// because our custom callback is flipping the result !test
return !test(value);
})
};
例如,如果您的数字数组是:
const nums = [1, 2, 3, 4, 5, 6]
并且您有一个函数isEven
,该函数接受一个数字,如果它是偶数,则返回true
;如果它不是偶数(即,奇数),则返回false
:
function isEven(num) {
return num % 2 === 0;
}
然后运行_.filter(arr, isEven)
将执行以下逻辑:
arr
以collection
的名称和isEven
以test
的名称result
的数组。遍历偶数中的每个数字
value
),检查调用test(value)
是否给出true
的结果。 test(value)
为真,则将数字(value
)添加到result
数组的末尾。collection
中的下一个数字返回result
数组。
因此,filter()
对数组中的每个数字执行isEven
函数,如果返回true
,则将其添加到新数组中(即:将其保留)。
_.reject()
与_.filter()
的作用相反-也就是说,它保留了回调函数为其返回false
的所有元素。如您所知_.filter()
保留为其返回true
的值,您可以通过取反_.filter()
返回的布尔值来使用test(value)
。这样,当test(value)
返回false
时,可以将其取为true
,使_.filter()
方法保留该元素。如果test(value)
返回true
,则将其取为false
,使过滤器方法放弃该value
。