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"]());

另见