如果`if`语句将'prompt`的返回值与数字进行比较,则永远不会执行

如果`if`语句将'prompt`的返回值与数字进行比较,则永远不会执行

问题描述:

我正在写游戏,但我遇到了这个问题:最后的 if 语句(及其所有 else if 语句)从未执行.

I am writing a game and I have this problem: the last if statement (and all its else if statements) are never executed.

这是无效的代码:

const compare = prompt("1.mars, 2.jupiter, 3.moon")

if (compare === 2) {
  confirm("your airplane crashed and you died")
} else if (compare === 1) {
  confirm("you arrived safely")
} else if (compare === 3) {
  confirm("you survived an airplane crash but you need to escape")
}

正如@Binkan Salaryman非常准确地指出,提示正在返回字符串('1','2'等).

As @Binkan Salaryman very accurately pointed out, prompt is returning a String ('1', '2', etc.).

使用 == 比较未键入的值(例如 compare == 2 )或与正确的类型进行比较:例如 compare ==='2'

Either use == to compare untyped values like compare==2 or compare with the correct type: e.g. compare==='2'