我不断收到“SyntaxError:Unexpected关键字'else'”的错误。任何人都可以帮我解释为什么这是?
// Check if the user is ready to play!
confirm("I am ready to play!");
var age = prompt("What's your age?");
if(age === 13)
{
console.log("You are allowed to play but at your own risk.");
}
else
{
console.log("Play on!");
}
console.log("You are at a Justin Bieber concert, and you hear this
lyric 'Lace my shoes off, start racing.'");
console.log("Suddenly, Bieber stops and says, 'Who wants to race me?'");
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(userAnswer === "no")
{
console.log("Oh no! Bieber shakes his head and sings 'I set a pace,
so I can race without pacing.'");
}
var feedback = prompt("Rate Game 1-10");
if(feedback > 8)
{
console.log("Thank you! We should race at the next concert!");
else(feedback < 8)
{
console.log("I'll keep practicing coding and racing.");
我不断收到“SyntaxError:Unexpected关键字'else'”的错误。任何人都可以帮我解释为什么这是?
答案 0 :(得分:1)
看到这段代码?
if(feedback > 8)
{
console.log("Thank you! We should race at the next concert!");
else(feedback < 8)
{
应该是:
if(feedback > 8)
{
console.log("Thank you! We should race at the next concert!");
}
else(feedback < 8)
{
您错过了}
。另外,请注意T.J.的评论。 else
没有条件,所以它应该是:
if(feedback > 8)
{
console.log("Thank you! We should race at the next concert!");
}
else
{
如果这是它在代码中的存在方式,则以下问题也存在问题,但我将假设它是一个复制/粘贴问题。除非你将其转义,否则不能将这样的字符串拆分为多行。
console.log("You are at a Justin Bieber concert, and you hear this
lyric 'Lace my shoes off, start racing.'");
答案 1 :(得分:1)
一些观察结果:
else
没有条件,所以像
else(userAnswer === "no")
不要做你认为他们做的事情,这会在以后导致语法错误。代替:
else if (userAnswer === "no")
您不能只在字符串文字的中间放置换行符,而不是使用"
或'
引用的字符串。 (你可以用ES6的新模板字符串引用```,但到目前为止支持很薄。)
缩进是你的朋友。用它。 http://jsbeautifier.org或任何一半体面的IDE都可以提供帮助。
...并查看Andy's answer关于遗失}
的内容,如果您使用缩进(上面的#3),这将更加明显。
答案 2 :(得分:0)
你的js中缺少关闭}
if(feedback > 8)
{
console.log("Thank you! We should race at the next concert!");
else(feedback < 8)
{
console.log("I'll keep practicing coding and racing.");
更正后的代码
if(feedback > 8)
{
console.log("Thank you! We should race at the next concert!");
}
else(feedback < 8)
{
console.log("I'll keep practicing coding and racing.");
}