javascript - Javascript中函数参数的评估顺序是什么?

标签 javascript

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

>> 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, 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 - Javascript中函数参数的评估顺序是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8405989/

相关文章:

javascript - d3 SVG 上的下拉菜单

javascript - 在 JavaScript 中按键排序数组

javascript - 使用 MixItUp 在一个网格中进行多种排序

javascript - 从 &lt;style&gt; 获取 css 作为输出文本

javascript - 加载模板和创建范围时应该使用 "controllers"还是 "directives"?

javascript - jQuery 对象不起作用

javascript - 如何在 Codeigniter 中创建 API?

javascript - 为什么这个 textarea 不用 .focus() 聚焦?

asp.net - 使用 JQuery 访问 ASP.net Web 服务时出错 - JSONP

PHP 强制下载和刷新解决方案不起作用