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" };