语法错误:左侧赋值无效
当某处发生意外分配时,会发生 JavaScript 异常 "左侧赋值无效"。当使用单个 =
符号而不是 ==
或 ===
时,可能会触发它。
¥The JavaScript exception "invalid assignment left-hand side" occurs when there was an unexpected assignment somewhere. It may be triggered when a single =
sign was used instead of ==
or ===
.
信息
错误类型
¥Error type
SyntaxError
或 ReferenceError
,具体取决于语法。
¥SyntaxError
or ReferenceError
, depending on the syntax.
什么地方出了错?
¥What went wrong?
某处有一个意想不到的任务。例如,这可能是由于 赋值运算符 和 相等运算符 不匹配造成的。虽然单个 =
符号将值分配给变量,但 ==
或 ===
运算符比较值。
¥There was an unexpected assignment somewhere. This might be due to a mismatch of an assignment operator and an equality operator, for example. While a single =
sign assigns a value to a variable, the ==
or ===
operators compare a value.
示例
典型的无效赋值
¥Typical invalid assignments
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
语句中,你要使用相等运算符 (===
),而对于字符串连接,需要使用加号 (+
) 运算符。
¥In the if
statement, you want to use an equality operator (===
), and for the string concatenation, the plus (+
) operator is needed.
if (Math.PI + 1 === 3 || Math.PI + 1 === 4) {
console.log("no way!");
}
const str = "Hello, "
+ "from the "
+ "other side!";
产生引用错误的作业
¥Assignments producing ReferenceErrors
无效的赋值并不总是会产生语法错误。有时语法几乎是正确的,但在运行时,左侧表达式的计算结果是一个值而不是引用,因此赋值仍然无效。此类错误会在执行稍后(即实际执行该语句时)发生。
¥Invalid assignments don't always produce syntax errors. Sometimes the syntax is almost correct, but at runtime, the left hand side expression evaluates to a value instead of a reference, so the assignment is still invalid. Such errors occur later in execution, when the statement is actually executed.
function foo() {
return { a: 1 };
}
foo() = 1; // ReferenceError: invalid assignment left-hand side
函数调用、new
调用、super()
和 this
都是值而不是引用。如果你想在左侧使用它们,则赋值目标需要是它们生成值的属性。
¥Function calls, new
calls, super()
, and this
are all values instead of references. If you want to use them on the left hand side, the assignment target needs to be a property of their produced values instead.
function foo() {
return { a: 1 };
}
foo().a = 1;
注意:在 Firefox 和 Safari 中,第一个示例在非严格模式下生成
ReferenceError
,在 严格模式 下生成SyntaxError
。Chrome 会为严格模式和非严格模式抛出运行时ReferenceError
。¥Note: In Firefox and Safari, the first example produces a
ReferenceError
in non-strict mode, and aSyntaxError
in strict mode. Chrome throws a runtimeReferenceError
for both strict and non-strict modes.
使用可选链作为分配目标
¥Using optional chaining as assignment target
可选链接 不是有效的分配目标。
¥Optional chaining is not a valid target of assignment.
obj?.foo = 1; // SyntaxError: invalid assignment left-hand side
相反,你必须首先保护无效的情况。
¥Instead, you have to first guard the nullish case.
if (obj) {
obj.foo = 1;
}