SyntaxError: missing variable name

JavaScript 异常“缺少变量名”是一个常见错误。它通常是由于省略了变量名或拼写错误造成的。

消息

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

错误类型

SyntaxError

哪里出错了?

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

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

示例

缺少变量名

js
const = "foo";

很容易忘记为变量赋值一个名称!

js
const description = "foo";

保留关键字不能作为变量名

有一些变量名是保留关键字。您不能使用这些关键字。抱歉 :(

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

声明多个变量

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

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

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

// SyntaxError: missing variable name

已修复版本

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

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

数组

JavaScript 中的 Array 字面量需要用方括号括起来。这行不通

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

这将是正确的

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

另见