语法错误:缺少变量名

JavaScript 异常 "缺少变量名" 是一个常见错误。它通常是由于省略变量名或印刷错误引起的。

¥The JavaScript exception "missing variable name" is a common error. It is usually caused by omitting a variable name or a typographic error.

信息

¥Message

SyntaxError: missing variable name (Firefox)
SyntaxError: Unexpected token '='. Expected a parameter pattern or a ')' in parameter list. (Safari)

错误类型

¥Error type

SyntaxError

什么地方出了错?

¥What went wrong?

变量缺少名称。原因很可能是拼写错误或忘记了变量名。确保你在 = 符号之前提供了变量名称。

¥A variable is missing a name. The cause is most likely a typo or a forgotten variable name. Make sure that you've provided the name of the variable before the = sign.

同时声明多个变量时,请确保前面的行/声明不是以逗号而不是分号结尾。

¥When declaring multiple variables at the same time, make sure that the previous lines/declaration does not end with a comma instead of a semicolon.

示例

¥Examples

缺少变量名

¥Missing a variable name

js
const = "foo";

很容易忘记为变量指定名称!

¥It is easy to forget to assign a name for your variable!

js
const description = "foo";

保留关键字不能是变量名

¥Reserved keywords can't be variable names

有几个变量名是 保留关键字。你不能使用这些。对不起 :(

¥There are a few variable names that are reserved keywords. You can't use these. Sorry :(

js
const debugger = "whoop";
// SyntaxError: missing variable name

声明多个变量

¥Declaring multiple variables

声明多个变量时要特别注意逗号。是否有多余的逗号,或者你使用逗号而不是分号?你是否记得为所有 const 变量赋值?

¥Pay special attention to commas when declaring multiple variables. Is there an excess comma, or did you use commas instead of semicolons? Did you remember to assign values for all your const variables?

js
let x, y = "foo",
const z, = "foo"

const first = document.getElementById("one"),
const second = document.getElementById("two"),

// SyntaxError: missing variable name

固定版本:

¥The fixed version:

js
let x,
  y = "foo";
const z = "foo";

const first = document.getElementById("one");
const second = document.getElementById("two");

数组

¥Arrays

JavaScript 中的 Array 文字需要用方括号将值括起来。这是行不通的:

¥Array literals in JavaScript need square brackets around the values. This won't work:

js
const arr = 1,2,3,4,5;
// SyntaxError: missing variable name

这是正确的:

¥This would be correct:

js
const arr = [1, 2, 3, 4, 5];

也可以看看

¥See also