【问题标题】:`if` statement comparing return value of `prompt` to number is never executed将“提示”的返回值与数字进行比较的“if”语句永远不会执行
【发布时间】:2015-07-06 07:59:14
【问题描述】:

我正在编写一个游戏,但我遇到了这个问题:最后一个 if 语句(及其所有 else if 语句)永远不会执行。

这是无效的代码:

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")
}

【问题讨论】:

  • prompt 查询一个字符串,但你与整数比较(例如:'1' === 1 等价于false)跨度>
  • 您可以将 if 语句更改为仅使用 == 而不是 ===,因此类型也不必匹配:if (compare == 2) ... 等

标签: javascript if-statement prompt


【解决方案1】:

正如@Binkan Salaryman 非常准确地指出的那样,prompt 正在返回一个字符串('1'、'2' 等)。

要么使用== 来比较像compare==2 这样的无类型值,要么与正确的类型进行比较:例如compare==='2'

【讨论】:

  • ==!= 几乎是 never recommended。它们并不总是直观地传递,因为它们经常不必要地执行类型强制。始终使用 ===!== 代替。使用Number(prompt()) 或与字符串进行比较。
【解决方案2】:

使用 Equality operator( == ) 而不是严格相等 ( === ) 运算符。使用===,只有当两个操作数的类型相同时,比较才会返回true。在您的情况下,提示的结果返回字符串,并且

compareInt === 2; // '2' === 2 

在您检查字符串和数字是否相同时返回false

'2' === 2 returns false as type checking is also done
'2' == 2 returns true as no type checking

【讨论】:

  • “因为没有类型检查” 是错误的。 ==!= 几乎是 never recommended。它们并不总是直观地传递,因为它们经常不必要地执行类型强制。始终使用 ===!== 代替。使用Number(prompt()) 或与字符串进行比较。
【解决方案3】:

我做了一个小演示。稍微重构了你的代码。 Demo

正如一些人指出的主要问题是prompt 返回一个string,即使你写一个number

您需要使用parseInt() 函数将此字符串转换为int

if(jack === 'yes'){
    var compare = parseInt(prompt("1.mars, 2.jupiter, 3.moon"));
    switch(compare){
        case 2: confirm("your airplane crashed and you died")
            break;
        case 1: confirm("you arrived safely")
            break;
        case 3: confirm("you survived an airplane crash but you need to escape")
            break;
        default:
            confirm("An error occured");
    }
}

【讨论】:

【解决方案4】:

试试:

compareInt = parseInt(compare)

最终代码如下:

var compare = prompt ("1.mars,2.jupiter,3.moon")
var compareInt = parseInt(compare);
if (compareInt===2) {confirm ("your airplane crashed and you died")}
else if (compareInt===1) {confirm ("you arrived safely")}
else if (compareInt===3){
confirm("you survived an airplane crash but you need to escape")} 

【讨论】:

    【解决方案5】:

    对于您的代码,您不需要通过 === 进行严格检查,您可以使用与 == 的简单比较

    • 因为 === 还会比较两者的类型以及值
    • == 只比较值

    【讨论】:

      猜你喜欢
      • 2019-07-24
      • 1970-01-01
      • 2016-12-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多