为什么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
为了解释一下,你在这里想念括号:
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;
0是假的,所以x
中的x && ...
是假的。