'其他'在我的if/else语句中,从来没有发生过——有人能解释为什么吗

The 'else' in my if/else statement never happens - can someone explain why?

本文关键字:能解释 为什么 我的 其他 if 语句 else 从来没有      更新时间:2024-01-30

只需完成codecademy课程,当我运行代码时,除了这个if/else语句外,一切都正常。到那时,无论我为userAnswer提示符输入什么,我都只得到"if"输出。有人能解释一下原因吗?我已经读了100遍了,但答案并没有让我大吃一惊。非常感谢。

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

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

将您的条件更改为

userAnswer === "yes"

if测试中,使用===进行比较。=进行赋值。

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

将if语句更改为

 userAnswer === "yes"

您在检查必须使用二重相等的条件时犯了一个小错误,即如果(username="yes")是错误的,我们如果(username=="yes"

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

相关文章: