简单的if-else语句总是返回true

时间:2014-10-13 15:08:15

标签: javascript html if-statement

我正在尝试创建一个简单的if-else语句,但是当我运行代码时,它总是返回true,即使我在提示符中输入了一些我知道应该是false的内容。我有ran it through JsFiddle,似乎代码段完全有效。

var captchaTest = 5;
var captchaInput = prompt('What is five plus five?');

if ('captchaTest + captchaInput = 10') {
    alert('You passed, you may continue'); window.location.href = 'pagepass.html';
}
else {
    alert('Failed, try again.'); window.location.href = 'main.html';
}

有人可以告诉我我做错了吗?

3 个答案:

答案 0 :(得分:6)

JavaScript中的非空字符串是 truthy 。评估为布尔值时,'captchaTest + captchaInput = 10'true

您需要删除引号并将=更改为==

if (captchaTest + captchaInput == 10)

答案 1 :(得分:1)

除了其他提供的答案之外,我还要指出,根据你的验证码问题,你的情况应该是这样的

if (captchaInput == 10){
  alert('You passed, you may continue'); window.location.href = 'pagepass.html';
}
else {
  alert('Failed, try again.'); window.location.href = 'main.html';
}

我没有看到使用变量captchaTest

答案 2 :(得分:0)

您不应该使用'captchaTest + captchaInput = 10',因为它是String并始终评估为true,除非它是空的。

此外,您应该使用比较运算符==而不是赋值运算符=

所以删除引号

if ((captchaTest + captchaInput) == 10)