訊息
SyntaxError: missing ) after condition (Firefox)
SyntaxError: Unexpected token '{'. Expected ')' to end an 'if' condition. (Safari)
錯誤型別
SyntaxError
哪裡出錯了?
if 條件的寫法有誤。在任何程式語言中,程式碼都需要根據不同的輸入做出決策並執行相應的操作。if 語句在指定條件為真時執行一個語句。在 JavaScript 中,這個條件必須出現在 if 關鍵字後的括號中,像這樣
js
if (condition) {
// do something if the condition is true
}
示例
缺少括號
這可能只是一個疏忽,請仔細檢查程式碼中的所有括號。
js
if (Math.PI < 3 {
console.log("wait what?");
}
// SyntaxError: missing ) after condition
要修復此程式碼,您需要新增一個括號來閉合條件。
js
if (Math.PI < 3) {
console.log("wait what?");
}
關鍵字“is”的誤用
如果您來自其他程式語言,也很容易新增在 JavaScript 中含義不同或根本沒有含義的關鍵字。
js
if (done is true) {
console.log("we are done!");
}
// SyntaxError: missing ) after condition
相反,您需要使用正確的比較運算子。例如
js
if (done === true) {
console.log("we are done!");
}
或者更好的是
js
if (done) {
console.log("we are done!");
}