我不明白为什么这段代码会在代码后面生成错误,我希望有人能帮助指出我的语法错误:
var userprompt = function() {
var num = prompt("Enter a number")
if (num % 7 == 0) {
console.log("Lucky, your number is divisiable by 7!");
};
else if (num % 2 == 0) {
console.log("Your number is an even number!");
};
else {
console.log("That number is not awesome.");
};
};
错误(由 Chrome JS 控制台产生)
SyntaxError: Unexpected token else
message: "Unexpected token else"
stack: (...)
get stack: function () { [native code] }
set stack: function () { [native code] }
__proto__: Error
**根据 Agrum 的建议编辑了代码,当在 Chrome JS Console 中运行时,唯一发生的事情就是弹出警报消息。
var userprompt = function() {
var num = prompt("Enter a number");
if (num % 7 == 0) {
console.log("Lucky, your number is divisiable by 7!")
}
else if (num % 2 == 0) {
console.log("Your number is an even number!")
}
else {
console.log("That number is not awesome.")
}
};
alert("This is a test");
这些 if 的结束括号后不需要分号。
if(true) { console.log("something"); }
不是
if(true) { console.log("something"); };
var userprompt = function() {
var num = prompt("Enter a number");
if (num % 7 == 0) {
console.log("Lucky, your number is divisiable by 7!");
}
else if (num % 2 == 0) {
console.log("Your number is an even number!");
}
else {
console.log("That number is not awesome.");
}
};
编辑:每条指令后还缺少一个分号。