语法错误:JavaScript中的意外标识符

时间:2015-02-08 21:49:45

标签: javascript

运行以下代码时出现语法错误:

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

代码比上面的代码多,但我知道错误源自那里。

2 个答案:

答案 0 :(得分:4)

您的if语法错误。它应该是这样的:

if (userAnswer === "yes")

答案 1 :(得分:1)

你的if-then语法似乎错了,它应该是if (expression) {} else {}。您还在if表达式(userAnswer = ("yes"))中使用赋值运算符,而不是测试相等性(userAnswer == "yes"

尝试以下方法:

if (userAnswer == "yes") {
    console.log("You and Bieber...")
}
else {
    console.log("Oh no! ...")
}