为什么在赋值中表达为左侧并不总是有效? [英] Why expression as left-hand side in assignment doesn't always work?
问题描述
此代码有效:
let foo;
(foo) = 'bar';
console.log(foo);
这让我相信任何表达式都可以作为赋值的左侧,但是,这段代码不起作用:
And that makes me believe that any expression works as a left-hand side in assignment, however, this code doesn't work:
let foo1 = "bar";
let foo2;
let foo3;
(foo1 && foo2 && foo3) = "foobar"; // The left-hand side evaluates to undefined which can't be assigned
console.log(foo1, foo2, foo3);
什么使左侧在赋值中有效,为什么它不能总是表达式?
What makes a left-hand side valid in an assignment, why it can't always be an expression?
推荐答案
规范的相关部分是 此处:
LeftHandSideExpression 的AssignmentTargetType 不简单是语法错误.
It is a Syntax Error if AssignmentTargetType of LeftHandSideExpression is not simple.
和此处.
简化版本是(如果我们不考虑解构)您可以为变量或对象的属性赋值.
The simplified version is that (if we leave destructuring aside) you can assign a value to a variable or to a property of an object.
给定(foo)
,括号没有意义,表达式只是一个变量名.这很好.
Given (foo)
, the parenthesis are pointless and the expression is just a variable name. This is fine.
给定 (foo1 && foo2 && foo3)
从变量中读取值,使用 &&
运算符和结果进行比较是一个值.
Given (foo1 && foo2 && foo3)
the values are read from the variables, compared using the &&
operator and the outcome is a value.
不能给值赋值,只能给属性或变量赋值.
You can't assign a value to a value, only to a property or a variable.
这篇关于为什么在赋值中表达为左侧并不总是有效?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!