JavaScript:为什么boolean总是返回true

JavaScript: why is boolean always returning true

本文关键字:返回 true boolean 为什么 JavaScript      更新时间:2023-10-11

当我用customerNumber的任何值运行它时,它总是返回if语句中的第一条警报消息。这里怎么了?

var customerNumbers = 13;
var winningNumbers = [];
winningNumbers.push(12, 17, 24, 37, 38, 43);
var match = false;
for (i=0; i<winningNumbers.length; i++) {
    if (winningNumbers[i] == customerNumbers) {
        match = true;
    }
}
if (match = true) {
    alert("This Week's Winning Numbers are:'n" + winningNumbers.toString() + 
    "'nThe Customer's Number is:'n" + customerNumbers + "'nWe have a match and a winner!");
}
else {
    alert("This Week's Winning Numbers are:'n" + winningNumbers.toString() + 
    "'nThe Customer's Number is:'n" + customerNumbers + "'nSorry, you are not a winner this week.");
}

您不是在比较布尔matchtrue,而是将true分配给布尔match。您需要使用double或triple=。

match = true // Sets match to true
match == true // Compares match to true
match === true // Strictly compares match to true

所以,再加上一些等号,它应该会起作用。

不要在if语句中使用赋值运算符(=)。使用相等运算符(===)。

if (match === true)