根据我的测试,它总是从左到右
>> console.log( console.log(1), console.log(2) );
1
2
undefined undefined
但我在 ECMAScript 标准中找不到确认这一点的相关部分。
最佳答案
JavaScript 中的所有运算符都从左到右计算其操作数,包括函数调用运算符。首先评估要调用的函数,然后按从左到右的顺序评估实际参数。
Section 11.2.3是相关的规范部分。
11.2.3 Function Calls
...
2 Let func be GetValue(ref).
3 Let argList be the result of evaluating Arguments, producing an internal list of argument values (see 11.2.4).
...
你可以看到ArgumentList产生式是左递归的
11.2.4 Argument lists
...
The production ArgumentList : ArgumentList
,
AssignmentExpression is evaluated as follows
和 ArgumentList 在 AssignmentExpression 之前计算,如下所示。
在 EcmaScript 3 下,一些比较运算符( <
、 <=
、 >
、 >=
)自 a<=b
起从右到左计算。定义为!(b<a)
,但这被广泛认为是一个规范错误,主要解释器并没有以这种方式实现它,并且它在 EcmaScript 5 中得到了修复。
来自语言规范:
11.8.5 The Abstract Relational Comparison Algorithm # Ⓣ
The comparison
x < y
, wherex
andy
are values, producestrue
,false
, orundefined
(which indicates that at least one operand isNaN
). In addition tox
andy
the algorithm takes a Boolean flag named LeftFirst as a parameter. The flag is used to control the order in which operations with potentially visible side-effects are performed uponx
andy
. It is necessary because ECMAScript specifies left to right evaluation of expressions. The default value of LeftFirst is true and indicates that thex
parameter corresponds to an expression that occurs to the left of they
parameter’s corresponding expression. If LeftFirst is false, the reverse is the case and operations must be performed upony
beforex
. Such a comparison is performed as follows:
关于javascript - Javascript 中函数参数的求值顺序是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60358745/