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)

错误类型

SyntaxErrorReferenceError,取决于语法。

哪里出错了?

某处发生了意外赋值。这可能是由于赋值运算符相等运算符不匹配,例如。虽然单个 = 符号将值赋给变量,但 ===== 运算符比较值。

示例

典型的无效赋值

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

另见