本文介绍了如果`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'

这篇关于如果`if`语句将'prompt`的返回值与数字进行比较,则永远不会执行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-21 06:29