如果在开关中声明

时间:2015-11-11 19:10:34

标签: javascript if-statement

我正在研究一个学习javascript课程的问题。我在尝试在交换机中添加if语句时遇到了麻烦。我目前有:

var user = prompt("Are you ready for battle?!").toUpperCase();
switch(user) {
    case'YES':
        if(YES && NO) {
           console.log("Great, let's do it.");
        } else {
            console.log("Bye");
        }
        console.log("Great! It will be a long exciting battle.");
        break;  
    case'NO':
        console.log("Come back when you are ready.");
        break;
    case'MAYBE':
        console.log("Go away. This is only for the brave");
        break;
        default:
        console.log("You obviously do not belong here. It was a simple yes/no question.")
}

问题是:

Add some if/else statements to your cases that check to see whether one
condition and another condition are true, as well as whether one condition 
or another condition are true. Use && and || at least one time each.

我得到的错误是:ReferenceError: YES is not defined

我可以在if条件中添加什么来完成这项工作,或者如何定义YES

1 个答案:

答案 0 :(得分:0)

看来你在这里遇到两个问题。

首先是评论中指出的问题,即您将YESNO视为变量,而不是。为了避免通过提供代码的更正版本来剥夺您学习的机会,我将仅提供相关示例。

var word = "test";
// If we compare against the string literally, it will have an error
// because it's looking for a variable with that name.
if (word === test) { } // ReferenceError: test is not defined

// we fix this by quoting what we're comparing against
if (word === "test") { } // Code inside the block would be executed :)

// But what about checking the value of "test" by itself?
// A string is "truthy", meaning that it passes the conditional test always.
if ("test") { } // Code would be executed always regardless of the content of var word

// Stringing multiple constants together doesn't make sense
if ("test" && "word") { } // This is equivalent...
if (true && true) { } // ... to this, which doesn't make sense

这将我们带到你想要解决的第二个问题。您的问题的要求指定检查一个条件和另一个条件是否为真,以及一个条件或另一个条件。问题是你只有一个条件来检查:变量user的状态。

如果你不知道它是什么,那么测试某些东西的情况才有意义。从用户收到的输入就是一个很好的例子。因此,我建议您从用户那里获取更多输入,例如姓名,年龄,性别,鞋码或其他任何内容。然后,您可以按如下方式检查条件:

// You would need to store user input in variables username and age previously... 
if (username === "vastlysuperiorman" && age < 13) { console.log("You're awfully young!"); }

// Or to only allow people within an age range... 
if (age < 13 || age > 31) { console.log("You must be between 13 and 31 years old to play this game!"); }

一旦你有多个条件需要检查,你可以在任何地方检查它们 - 在函数内部,在case语句中,在另一个if内。没关系。只需添加if块并测试条件即可。 :)