语法错误:缺少:属性 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.
信息
错误类型
什么地方出了错?
¥What went wrong?
使用 对象初始值设定项 语法创建对象时,冒号 (:
) 分隔对象属性的键和值。
¥When creating objects with the object initializer syntax,
a colon (:
) separates keys and values for the object's properties.
const obj = { propertyKey: "value" };
示例
冒号与等号
¥Colons vs. equal signs
此代码失败,因为在此对象初始值设定项语法中不能以这种方式使用等号。
¥This code fails, as the equal sign can't be used this way in this object initializer syntax.
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.
const obj = { propertyKey: "value" };
或者:
¥Or alternatively:
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:
const obj = { "b"+"ar": "foo" };
// SyntaxError: missing : after property id
将表达式放在方括号 []
中:
¥Put the expression in square brackets []
:
const obj = { ["b" + "ar"]: "foo" };
也可以看看
¥See also