_.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]);
例如,我测试我的函数,得到断言为 true,但我不明白这是如何工作的
最佳答案
Reject 只是重用过滤器完成的一些逻辑。它可以很容易地写成这样:
_.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);
})
};
关于javascript - 函数内的 Underscore.js 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60482381/