我的if / else语句中的'else'永远不会发生 - 有人可以解释为什么吗?

时间:2015-02-18 18:47:26

标签: javascript

只是执行codecademy课程,当我运行除if / else语句之外的代码时,一切正常。当它达到目标时,无论我为userAnswer提示输入什么,我都会得到' if'输出。有人可以解释原因吗?一直在读这个东西100x,答案是不会跳出来的。非常感谢。

var userAnswer = prompt("Do you want to race Bieber on stage?");

if(userAnswer="yes") {

    console.log("You and Bieber start racing. It's neck and neck! You win by a shoelace!")

} else {

    console.log("Oh no! Bieber shakes his head and sings 'I set a pace, so I can race without pacing.'")

}

4 个答案:

答案 0 :(得分:5)

您正在设置userAnswer而不是阅读其状态。

将条件更改为

userAnswer === "yes"

答案 1 :(得分:3)

if测试中,使用===进行比较。 =进行了分配。

(您也可以使用==,但这是===的部分损坏版本。)

答案 2 :(得分:0)

将if语句更改为

 userAnswer === "yes"

答案 3 :(得分:0)

如果(用户名===“是”)

var userAnswer = prompt("Do you want to race Bieber on stage?");

if(userAnswer==="yes") {

console.log("You and Bieber start racing. It's neck and neck! You win by a shoelace!")
}

else {

console.log("Oh no! Bieber shakes his head and sings 'I set a pace, so I can race without pacing.'")
}