简单的问题:
我可以否定在 array.filter() 语句中返回 true
或 false
的回调函数吗?例如
//the callback function
function isEven(element, index, array){
if (index%2 == 0 || index == 0){
return true;
}
return false;
}
//what i want to do with that function
//arr[i] is a string
var evens = arr[i].split("").filter(isEven); //works
var odds = arr[i].split("").filter(!isEven); // doesn't work
上面的行给了我错误TypeError: false is not a function
有一些背景的问题:
我正在接受一些 Hackerrank 挑战,并且遇到了一个需要获取字符串并对其进行处理的练习,因此输出为:具有偶数索引值的字符生成一个新字符串,奇数索引中的字符生成一个新字符串。位置组成另一个字符串,0 算偶数。
输入
airplane
输出
evens = 'arln'
odds = 'ipae'
我已经通过循环遍历字符串,评估索引,然后将值推送到相应的新数组(我稍后将其转换为字符串)来解决它,但我想到我可以用更多的方式来完成函数式方式,使用 Array.prototype.filter() 函数。
现在我创建一个新函数来评估索引号是否为偶数,我想使用相同的函数来填充两个数组(偶数和奇数),如下所示(现在您可以引用简单的问题部分):
var evens = arr[i].split("").filter(isEven); //works
var odds = arr[i].split("").filter(!isEven); // doesn't work
最佳答案
最简单的方法是传递一个匿名函数,该函数返回 isEven
的否定结果。
var evens = arr[i].split("").filter(function(el, index, array) {
return !isEven(el, index, array);
});
但是您可以更进一步,编写一个 not
函数,该函数本质上为您生成匿名函数。这是此类函数的示例。
var input = [0, 1, 2, 3, 4, 5];
function isEven(value) {
return value % 2 === 0;
}
function not(f) {
return function() {
return !f.apply(null, arguments);
}
}
var output = input.filter(not(isEven));
console.log(output);
如果您所在的环境支持rest parameters那么你可以像这样编写你的 not
函数。
var input = [0, 1, 2, 3, 4, 5];
function isEven(value) {
return value % 2 === 0;
}
function not(f) {
return function(...args) {
return !f.apply(null, args);
}
}
var output = input.filter(not(isEven));
console.log(output);
关于javascript - 取消回调函数的返回值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37399613/