JavaScript:为什么boolean总是返回true

时间:2015-02-12 14:47:53

标签: javascript if-statement for-loop boolean

当我使用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.");
}

2 个答案:

答案 0 :(得分:2)

您没有将您要分配match的布尔truetrue与布尔值match进行比较。你需要使用double或triple =。

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

所以添加更多相同的标志,它应该有用。

答案 1 :(得分:1)

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

if (match === true)