SyntaxError: identifier starts immediately after numeric literal
當識別符號以數字開頭時,會發生 JavaScript 異常 "identifier starts immediately after numeric literal"(識別符號緊跟在數字字面量之後)。識別符號只能以字母、下劃線 (_) 或美元符號 ($) 開頭。
訊息
SyntaxError: Invalid or unexpected token (V8-based) SyntaxError: identifier starts immediately after numeric literal (Firefox) SyntaxError: No identifiers allowed directly after numeric literal (Safari)
錯誤型別
SyntaxError
哪裡出錯了?
變數的名稱,稱為識別符號,遵循某些規則,你的程式碼必須遵守這些規則!
JavaScript 識別符號必須以字母、下劃線 (_) 或美元符號 ($) 開頭。它們不能以數字開頭!只有後續字元可以是數字 (0-9)。
示例
以數字字面量開頭的變數名
在 JavaScript 中,變數名不能以數字開頭。以下程式碼會失敗:
js
const 1life = "foo";
// SyntaxError: identifier starts immediately after numeric literal
const foo = 1life;
// SyntaxError: identifier starts immediately after numeric literal
你需要重新命名變數以避免以數字開頭。
js
const life1 = "foo";
const foo = life1;
在 JavaScript 中,對數字呼叫屬性或方法時存在一個語法上的特殊性。如果你想對整數呼叫方法,你不能在數字之後立即使用點,因為點被解釋為小數部分的開始,導致解析器將方法名稱視為緊跟在數字字面量之後的識別符號。為了避免這種情況,你需要將數字用括號括起來,或者使用雙點,其中第一個點是數字字面量的小數點,第二個點是屬性訪問器。
js
alert(typeof 1.toString())
// SyntaxError: identifier starts immediately after numeric literal
對數字呼叫方法的正確方式
js
// Wrap the number in parentheses
alert(typeof (1).toString());
// Add an extra dot for the number literal
alert(typeof 2..toString());
// Use square brackets
alert(typeof 3["toString"]());