如果语句在交换机块中javascript

时间:2015-11-18 19:31:19

标签: javascript if-statement switch-statement conditional

是否可以在Javascript的switch块中使用来自switch块的响应来使用if / else语句?以下是我尝试这样做的方法。这是一个CodeAcademy项目,您必须使用切换块和条件语句编写自己的冒险。

var user = prompt("You awake; dazed, blurred and lost. What do you do?").toLowerCase()
var day = 0;

switch (user) {
    case "look at the time":
        console.log("Good start, how long was I out for?");
        if (
        case "look at the time" && day === 0) {
            console.log("it's only been a few hours, but time is still ticking");
            day++
        } else if (day > 0) {
            console.log("it's been " + day + "s! Will I make it out of here");
            day++
        }
        break;
    case "figure out where I am":
        console.log("Yeah, how did I end up here in the first place?");
        if (
        case "figure out where I am" && day === 0) {
            console.log("This is a good checkpoint");
            day++
        }
        break;
    case 'run':
        console.log("Dry your eyes, find a direction, and hope for the best");
        break;
    case 'give up':
        console.log('Thanks for trying, have fun, where ever you are...');
        break;
    default:
        console.log("you fall back unconscious, hoping to wake again");
        day++;
        if (
        default) {
            return user;
        }
        if (
        case 'run' ||
        case 'give up') {
            console.log("It would have ended up coming down to this option anyway");
        }
}

1 个答案:

答案 0 :(得分:0)

如果您进行更改以停止在case语句中使用单词if,它将会起作用,例如它应该看起来像这样执行与user变量的比较案例陈述:

if (user === "look at the time" && day === 0) {
    console.log("it's only been a few hours, but time is still ticking");
    day++
} else if (day > 0) {
    console.log("it's been " + day + "s! Will I make it out of here");
    day++
}

在这种情况下,比较user === "look at the time"是多余的,因为该逻辑已在switch语句本身中进行评估。我刚刚将其包含在内,以便您可以看到如何与user变量进行比较,但可以将其完全排除,并在此情况下具有相同的效果。