为什么这两个if语句有不同的含义?

时间:2017-03-14 19:44:59

标签: javascript

我们来看代码

 var dumb = [1,2,3,4,5,6]

 for (var x = 0; x < dumb.length; x++){
    if (dumb[x] % 2) {
       console.log(dumb[x]);
    }
}

在上述程序中,它产生(1,3,5) 但如果if语句是:(如果dumb [x]%2 === 0),则产生(2,4,6)

为什么

    if (dumb[x] % 2) 

    if (dumb[x] % 2 === 0) 

产生不同的结果?

2 个答案:

答案 0 :(得分:2)

JavaScript 0中的条件语句为false,其他所有数字均为true

if (dumb[x] % 2) // if the numbers is even, it's false because the remainder is 0. 

if (dumb[x] % 2 === 0) 
//if even it's true, because the remainder 0 which is what you are comparing it to. 

答案 1 :(得分:1)

您正在比较模运算符的输出与布尔表达式的输出。

dumb[x] % 2 

计算出一个数字,而

dumb[x] % 2 === 0

可以使用布尔值,true或false。

如果第一个表达式为0,那么它将是假的,否则它将是真的。