这个IF / OR语句的语法是错误的吗?

时间:2014-08-20 02:30:20

标签: javascript if-statement

此代码有什么问题?

var variable = prompt("Choose answer1, answer2, answer3 or answer4");
if ((variable !== "answer1") || (variable !== "answer2") || (variable !== "answer3") || (variable !== "answer4")) {
    return "You must choose one of these four options!"
}

1 个答案:

答案 0 :(得分:1)

您当前的解决方案将始终为真,因为变量不会同时为所有答案。

您可以使用==而不是!==然后否定整个表达式:

if (!((variable == "answer1") || (variable == "answer2") || (variable == "answer3") || (variable == "answer4"))) {

或使用而不是或

if ((variable !== "answer1") && (variable !== "answer2") && (variable !== "answer3") && (variable !== "answer4")) {

在这两种情况下,如果表达式不是任何答案,则表达式将为true;如果是一个答案,则表达式为false。