ECMAScript 2015:const in for循环 [英] ECMAScript 2015: const in for loops

查看:163
本文介绍了ECMAScript 2015:const in for循环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

下面的两个(或两者/两者)代码片段中的哪一个应该在完整的ECMAScript 2015实现中工作:



for(const (a)a)(i = a; i = 1; i = a; a,a,a,a,b, )



根据我的理解,第一个例子应该工作,因为 e 被初始化为每次迭代。在第二个版本中,对于 i 也不是这样吗?



我感到困惑,因为现有的实现(Babel,IE,Firefox,Chrome,ESLint)似乎并不一致,并且具有完全实现 const ,具有两种循环变体的各种行为;我也不能在标准中找到具体的一点,所以这将是非常感激的。

解决方案

-of循环工程:

  for(const e of a)

ES6规范描述为:


ForDeclaration:LetOrConst ForBinding


http://www.ecma-international.org/ecma-262/6.0/index.html#sec-for-in-and-for -of-statements-static-semantics-boundnames



命令式循环不起作用:

  for(const i = 0; i   

这是因为在执行循环体之前,声明只进行一次评估。



http://www.ecma-international.org/ecma-262/6.0/index.html#sec-for-statement-runtime-semantics-labelledevaluation


Which of the two (or neither/ both) code fragments below should be working in a complete ECMAScript 2015 implementation:

for (const e of a)

for (const i = 0; i < a.length; i += 1)

From my understanding, the first example should work because e is initialized for each iteration. Shouldn't this also be the case for i in the second version?

I'm confused because existing implementations (Babel, IE, Firefox, Chrome, ESLint) do not seem to be consistent and have a complete implementation of const, with various behaviours of the two loop variants; I'm also not able to find a concrete point in the standard, so that would be much appreciated.

解决方案

The following for-of loop works:

for (const e of a)

The ES6 specification describes this as:

ForDeclaration : LetOrConst ForBinding

http://www.ecma-international.org/ecma-262/6.0/index.html#sec-for-in-and-for-of-statements-static-semantics-boundnames

The imperative for loop will not work:

for (const i = 0; i < a.length; i += 1)

This is because the declaration is only evaluated once before the loop body is executed.

http://www.ecma-international.org/ecma-262/6.0/index.html#sec-for-statement-runtime-semantics-labelledevaluation

这篇关于ECMAScript 2015:const in for循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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