SyntaxError: invalid assignment left-hand side
當某處出現意外賦值時,會發生 JavaScript 異常“左側賦值無效”。這可能是因為使用了單個 = 符號而不是 == 或 ===。
訊息
SyntaxError: Invalid left-hand side in assignment (V8-based) SyntaxError: invalid assignment left-hand side (Firefox) SyntaxError: Left side of assignment is not a reference. (Safari) ReferenceError: Invalid left-hand side in assignment (V8-based) ReferenceError: cannot assign to function call (Firefox) ReferenceError: Left side of assignment is not a reference. (Safari)
錯誤型別
SyntaxError 或 ReferenceError,取決於語法。
哪裡出錯了?
某處發生了意外賦值。這可能是由於賦值運算子和相等運算子不匹配,例如。雖然單個 = 符號將值賦給變數,但 == 或 === 運算子比較值。
示例
典型的無效賦值
js
if (Math.PI + 1 = 3 || Math.PI + 1 = 4) {
console.log("no way!");
}
// SyntaxError: invalid assignment left-hand side
const str = "Hello, "
+= "is it me "
+= "you're looking for?";
// SyntaxError: invalid assignment left-hand side
在 if 語句中,您想使用相等運算子 (===),而對於字串連線,需要加號 (+) 運算子。
js
if (Math.PI + 1 === 3 || Math.PI + 1 === 4) {
console.log("no way!");
}
const str = "Hello, "
+ "from the "
+ "other side!";
產生 ReferenceErrors 的賦值
無效賦值不總是產生語法錯誤。有時語法幾乎正確,但在執行時,左側表示式求值為一個值而不是一個引用,因此賦值仍然無效。此類錯誤在語句實際執行時,會在執行後期發生。
js
function foo() {
return { a: 1 };
}
foo() = 1; // ReferenceError: invalid assignment left-hand side
函式呼叫、new 呼叫、super() 和 this 都是值而不是引用。如果您想在左側使用它們,賦值目標需要是它們產生的值的屬性。
js
function foo() {
return { a: 1 };
}
foo().a = 1;
注意:在 Firefox 和 Safari 中,第一個示例在非嚴格模式下產生 ReferenceError,在嚴格模式下產生 SyntaxError。Chrome 在嚴格模式和非嚴格模式下都丟擲執行時 ReferenceError。
使用可選鏈作為賦值目標
可選鏈不是有效的賦值目標。
js
obj?.foo = 1; // SyntaxError: invalid assignment left-hand side
相反,您必須首先保護空值情況。
js
if (obj) {
obj.foo = 1;
}