语法错误:缺少:属性 id 之后

当使用 对象初始值设定项 语法创建对象时,会发生 JavaScript 异常 "缺少:属性 id 之后"。冒号 (:) 分隔对象属性的键和值。不知何故,这个冒号丢失或放错了地方。

¥The JavaScript exception "missing : after property id" occurs when objects are created using the object initializer syntax. A colon (:) separates keys and values for the object's properties. Somehow, this colon is missing or misplaced.

信息

¥Message

SyntaxError: Invalid shorthand property initializer (V8-based)
SyntaxError: missing : after property id (Firefox)
SyntaxError: Unexpected token '='. Expected a ':' following the property name 'x'. (Safari)
SyntaxError: Unexpected token '+'. Expected an identifier as property name. (Safari)

错误类型

¥Error type

SyntaxError

什么地方出了错?

¥What went wrong?

使用 对象初始值设定项 语法创建对象时,冒号 (:) 分隔对象属性的键和值。

¥When creating objects with the object initializer syntax, a colon (:) separates keys and values for the object's properties.

js
const obj = { propertyKey: "value" };

示例

¥Examples

冒号与等号

¥Colons vs. equal signs

此代码失败,因为在此对象初始值设定项语法中不能以这种方式使用等号。

¥This code fails, as the equal sign can't be used this way in this object initializer syntax.

js
const obj = { propertyKey = "value" };
// SyntaxError: missing : after property id

正确的方法是在创建对象后使用冒号或方括号来分配新属性。

¥Correct would be to use a colon, or to use square brackets to assign a new property after the object has been created already.

js
const obj = { propertyKey: "value" };

或者:

¥Or alternatively:

js
const obj = {};
obj.propertyKey = "value";

计算属性

¥Computed properties

如果从表达式创建属性键,则需要使用方括号。否则无法计算属性名称:

¥If you create a property key from an expression, you need to use square brackets. Otherwise the property name can't be computed:

js
const obj = { "b"+"ar": "foo" };
// SyntaxError: missing : after property id

将表达式放在方括号 [] 中:

¥Put the expression in square brackets []:

js
const obj = { ["b" + "ar"]: "foo" };

也可以看看