取反回调函数 Return 值

Negating Callback Function Return Value

直截了当的问题:

我可以否定 returns truefalse o array.filter() 语句的回调函数吗?例如

//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 odds = arr[i].split("").filter(function(a, index, array) {
  return !isEven(a, index, array);
});

简单示例:

Working Example

function isEven(n) {
  return n % 2 === 0;
}

var arr = [0,1,2,3,4,5,6,7,8,9];

var a = arr.filter(isEven);

var b = arr.filter(function(a) {
  return !isEven(a);
});

最简单的方法是传递一个匿名函数,该函数 returns 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);

我使用的解决方案是这样的:

var numbers = [0,1,2,3,4,5];
var evens = [];
var odds = [];

function isEvenOrNot(getEven) {
    return function(num) {
        if (num % 2 == 0 || num == 0){
            return true;
        }
        return false;
    }
}

evens = numbers.filter(isEvenOrNot(true));
odds = numbers.filter(isEvenOrNot(false));

console.log(evens); // [0,2,4]
console.log(odds); // [1,3,5]