SyntaxError: missing : after property id

JavaScript 异常“missing : after property id”在用对象初始化器语法创建对象时发生。冒号(:)用于分隔对象属性的键和值。在某些情况下,此冒号缺失或放置错误。

消息

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)

错误类型

SyntaxError

哪里出错了?

在使用对象初始化器语法创建对象时,冒号(:)用于分隔对象属性的键和值。

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

示例

冒号与等号

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

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

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

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

或者

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

计算属性

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

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

将表达式放在方括号 []

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

另见