比较' prompt '的返回值和number的' if '语句永远不会执行

`if` statement comparing return value of `prompt` to number is never executed

本文关键字:永远 执行 语句 prompt 返回值 比较 number if      更新时间:2023-09-26

我正在编写一款游戏,我遇到了这样的问题:最后一个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")
}

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

使用==来比较未类型化的值,如compare==2,或与正确的类型进行比较,如compare==='2'

使用相等运算符(==)代替严格相等运算符(===)。对于===,只有当两个操作数的类型相同时,比较才返回true。在您的示例中,prompt的结果返回string,而

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

返回false,因为您正在检查字符串和数字是否相同。

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

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

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

您需要使用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");
    }
}

尝试:

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

对于您的代码,您不需要严格检查===,您可以使用与==

的简单比较
  • 因为===将比较两者的类型以及值
  • ==只比较
  • 的值