Javascript中函数参数的评估顺序是什么? [英] What is the order of evaluation for function arguments in Javascript?

查看:162
本文介绍了Javascript中函数参数的评估顺序是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

根据我的测试,它总是从左到右

According to my tests it is always left-to-right

>> console.log( console.log(1), console.log(2) );
1
2
undefined undefined

但我不能找到相关部分在ECMAScript标准中确认这一点。

but I can't find the relevant section confirming this in the ECMAScript standard.

推荐答案

JavaScript中的所有运算符从左到右评估其操作数,包括函数调用运算符。首先,按从左到右的顺序评估调用函数,然后计算实际参数。

All the operators in JavaScript evaluate their operands left-to-right, including the function call operator. First the function to call is evaluated then the actual parameters in left-to-right order.

第11.2.3节是相关规范部分。


11.2.3函数调用

...

2让 func 成为 GetValue(ref)

3让 argList 成为评估 Arguments 的结果,产生一个参数值的内部列表(见11.2.4)。

3 Let argList be the result of evaluating Arguments, producing an internal list of argument values (see 11.2.4).

...

你可以看到 ArgumentList 生产是左递归的

and you can see that the ArgumentList production is left-recursive


11.2.4参数列表

...

生产 ArgumentList ArgumentList AssignmentExpression 评估如下

ArgumentList 进行评估以下措辞中的 AssignmentExpression ..

and ArgumentList is evaluated before AssignmentExpression in the following verbiage..

在EcmaScript 3下的一些比较运算符(< < = > > = )从右到左评估,因为 a< = b 是按定义的!(b< a),但这被广泛认为是一个规范错误,主要的解释器没有这样实现,并且它已在EcmaScript 5中修复。

Under EcmaScript 3 some of the comparison operators (<, <=, >, >=) evaluated right to left since a<=b was defined in terms of !(b<a), but that was widely recognized as a spec error, major interpreters did not implement it that way, and it was fixed in EcmaScript 5.

从语言规范:


11.8.5抽象关系比较算法#Ⓣ

比较 x< y ,其中 x y 是值,产生 true false ,或 undefined (表示至少有一个操作数的NaN )。除了 x y 之外,算法还将一个名为 LeftFirst 的布尔标志作为参数。该标志用于控制在 x y 上执行具有潜在可见副作用的操作的顺序。 这是必要的,因为ECMAScript指定从左到右的表达式评估。 LeftFirst 的默认值为true,表示 x 参数对应于 y 参数对应表达式左侧的表达式。如果 LeftFirst 为false,则情况相反,必须在 y 之前执行操作 x 。这样的比较如下:

The comparison x < y, where x and y are values, produces true, false, or undefined (which indicates that at least one operand is NaN). In addition to x and y 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 upon x and y. It is necessary because ECMAScript specifies left to right evaluation of expressions. The default value of LeftFirst is true and indicates that the x parameter corresponds to an expression that occurs to the left of the y parameter’s corresponding expression. If LeftFirst is false, the reverse is the case and operations must be performed upon y before x. Such a comparison is performed as follows:

这篇关于Javascript中函数参数的评估顺序是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆