[英]Why the following JavaScript code is not valid?
When the following code is executed in chrome console 在Chrome控制台中执行以下代码时
let a, b, c;
b = 2;
a = b+1 = c = 2+3;
It says an error 'Invalid left-hand side assignment' for the last statement. 它为最后一条语句显示错误“无效的左侧分配”。 But when we execute the below-given code it accepts it and does not show any error.
但是,当我们执行下面给出的代码时,它会接受它并且不会显示任何错误。
let a, b, c;
a = b = c = 2+3;
assignment '=' is an operator so according to operator precedence in javascript, it should work fine. 赋值'='是一个运算符,因此根据javascript中的运算符优先级,它应该可以正常工作。 what do you guys think, what is the problem?
你们怎么看,出什么问题了?
for the first code you would need to do 对于第一个代码,您需要执行
let a,b,c;
b=2;
a=b+1;
c=5;
doing 干
a=b=c=2+3
A = B = C = 2 + 3
works because you arent altering a value to the left of the last equal 之所以有效,是因为您没有更改最后一个等号左边的值
the =
operator calculate first the right side and require the left side to be lvalue . =
运算符首先计算右侧,并要求左侧为左值 。
In your second example for every assignment operator the left side is always a variable, so it works fine. 在第二个示例中,对于每个赋值运算符,左侧始终是变量,因此可以正常工作。 but in the first example:
但在第一个示例中:
let a, b, c;
让a,b,c;
b = 2;
b = 2;
a = b+1 = c = 2+3;
a = b + 1 = c = 2 + 3;
you trying to assign 5 into b+1
, its simply not a variable. 您试图将5分配给
b+1
,它根本不是变量。
您只需要一些括号即可清楚说明您的意思:
a = 1 + (b = c = 2+3);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.