【发布时间】:2015-11-18 19:31:19
【问题描述】:
是否可以在 Javascript 的 switch 块中使用来自 switch 块的响应的 if/else 语句?以下是我的尝试。这是一个 CodeAcademy 项目,您必须在其中使用 switch 块和条件语句编写自己的冒险代码。
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");
}
}
【问题讨论】:
-
您无需再次检查(也不能)
case,只需检查day。 -
不,不能将 if 语句放在
switch块内。您只能将cases 放在那里。而且您也不能将cases 放在if-conditions 中。这只是一个语法错误。
标签: javascript if-statement switch-statement conditional