为什么在 array.filter 中得到这个结果?为什么函数返回偶数?函数 (2%2) 中的第一个元素等于 0, 0 - 1 = -1 ,是负数。应过滤负数。
var c = new Array(1, 2, 3, 4, 5, 6);
var b = c.filter(function(a) {
return (a % 2) - 1;
});
//output [2,4,6]
我不太明白,请帮帮我
其他示例
let c = new Array(10, 20, 30, 40, 50, 60, 70, 80);
var b = c.filter(function(a) {
return (a % 20) - 10; // but if it is 9, it returns the whole list, it does not filter anything.
});
console.log(b); // [ 20, 40, 60, 80 ]
最佳答案
%
是余数(如果除以右边的数字) 运算符。 oddNumber % 2
始终产生余数 1
。 1 - 1 === 0
并且是错误的。 evenNumber % 2
是余数0
。 0 - 1 === -1
,这是真的。当然,我假设您在数组中使用正数,而不是负数。
关于javascript - 为什么在 array.filter, lambda 中得到这个结果? javascript,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60824932/