如何否定布尔函数?
这样使用类似的东西:
_.filter = function(collection, test) {
var tmp = []
_.each(collection, function(value){
if (test(value)) {
tmp.push(value);
}
})
return tmp
};
var bag = [1,2,3];
var evens = function(v) { return v % 2 === 0};
Run Code Online (Sandbox Code Playgroud)
这是错的:
// So that it returns the opposite of evens
var result = _.filter(bag, !evens);
Run Code Online (Sandbox Code Playgroud)
结果:
[1,3]
Run Code Online (Sandbox Code Playgroud)
Underscore有一个.negate()API:
_.filter(bag, _.negate(evens));
Run Code Online (Sandbox Code Playgroud)
你当然可以把它藏为自己的谓词:
var odds = _.negate(evens);
Run Code Online (Sandbox Code Playgroud)
然后
_.filter(bag, odds);
Run Code Online (Sandbox Code Playgroud)