【发布时间】:2020-06-17 01:57:03
【问题描述】:
我需要知道 operator Associativity 是否与 JavaScript 中赋值运算符和其他运算符的 求值顺序 相同
var x;
x = 10;
在上面的代码中,我需要知道赋值表达式x = 10;是从“从右到左”还是从“从左到右”执行的,因为运算符关联性赋值运算符的“从右到左” 我有点担心像x = 10; 这样的正常赋值表达式是如何执行的。它是从“右到左”还是“从左到右”执行的,如下面的代码,您可以看到赋值表达式是从右到左执行的。
var y;
var z;
y = z = 10; // In this snippet you can see that both the variables "y" and "z" hold the value of number 10 this means that the Assignment operator is executed from "right to left";
// Now i must know whether a normal Assignment operator is also executed from "right to left" because Assignment operator is having "right to left" Associativity;
var c;
c = 10; // Not sure whether how and to which side this assignment expression is executed is it executed from "left to right" or "right to left"
【问题讨论】:
-
如果 JS 中的“从左到右”分配有效,那么
10 = x应该可以完美运行。 -
无论表达式中包含多少操作,JavaScript 中的赋值运算符都是右关联的:
a = b = 10;和a = 10;都是右关联的。您可以在 MDN 上查看 op 表和每个运算符的关联性:developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/… -
@HunterMcMillen 你好,所以你的意思是正常的赋值表达式也是从“右到左”执行的
-
@AlexMichailidis 我认为在你的情况下赋值表达式是从“左到右”执行的,因为首先它必须检查左操作数,这通常是一个变量,但在你的情况下它是一个数字。数字“10”所以因为赋值运算符是从左到右执行的,只有你的代码给出了错误
-
等号的右侧分配给左侧。别想太多了
标签: javascript operator-precedence assignment-operator associativity order-of-execution