为什么过滤器不能捕获0并返回两个数字,而不是三个?

问题描述 投票:0回答:2

为什么0 && 0%2 === 0返回0而不是真的?并且数字0不会在filter()之后落入数组中。

/*
    0%2 returns 0;
    0 && 0%2 returns 0; 
    0 && 0%2 === 0 returns 0 instead true;
    0 === 0 returns true. I am confused.
*/
const y = ['0','1','2','3','4','5']
.map(x => +x)                       // [0,1,2,3,4,5]
.filter(x => x && x % 2 === 0)      // [2,4] ,instead [0,2,4]
.reduce((accum, item)=> accum * item); // 8
console.log(y); //8
javascript
2个回答
2
投票

为了解释一下,你在这里想念括号:

 0 && 0%2 returns 0; 
 0 && 0%2 === 0 returns 0 instead true;

带括号:

(0 && 0%2) === 0 returns true;

发生这种情况是因为在您的示例中,比较发生在逻辑和之前。所以基本上:

0%2 === 0 returns true;
0 && true returns 0;

2
投票

0是假的,所以x中的x && ...是假的。

© www.soinside.com 2019 - 2024. All rights reserved.