Javascript if语句不起作用

时间:2015-07-06 07:59:15

标签: javascript if-statement

你好,我正在写一个游戏,我有这个问题:我的if语句根本不起作用所以我决定寻求帮助。 这是不起作用的代码:

if (jack === "yes") {
  var 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")
}

P.S最后三个if语句不起作用。我尝试了很多东西,但没有任何帮助。

5 个答案:

答案 0 :(得分:0)

尝试:

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

答案 1 :(得分:0)

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

使用==比较compare==2等无类型值,或与正确的类型进行比较:例如compare==='2'

答案 2 :(得分:0)

为了您的代码,您不需要通过 === 进行严格检查,您可以使用 ==

进行简单比较
  • 因为 === 会比较两种类型以及值
  • == 仅比较值

答案 3 :(得分:0)

使用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

答案 4 :(得分:0)

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

有些人指出的主要问题是即使你写了try { CPropertySheet::OnInitDialog(); } catch (...) { //need to know what did catch. } prompt也会返回string

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

parseInt()