for 循环中的 let 关键字 [英] let keyword in the for loop

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

问题描述

ECMAScript 6 的 let 应该提供块作用域而不会带来麻烦.有人可以解释为什么在函数中 i 下面的代码中解析为循环中的最后一个值(就像使用 var 一样)而不是当前迭代中的值?

ECMAScript 6's let is supposed to provide block scope without hoisting headaches. Can some explain why in the code below i in the function resolves to the last value from the loop (just like with var) instead of the value from the current iteration?

"use strict";
var things = {};
for (let i = 0; i < 3; i++) {
    things["fun" + i] = function() {
        console.log(i);
    };
}

things["fun0"](); // prints 3
things["fun1"](); // prints 3
things["fun2"](); // prints 3

根据 MDN 在使用 let像这样的 for 循环应该在循环体的范围内绑定变量.当我在块内使用临时变量时,事情会像我期望的那样工作.为什么有必要?

According to MDN using let in the for loop like that should bind the variable in the scope of the loop's body. Things work as I'd expect them when I use a temporary variable inside the block. Why is that necessary?

"use strict";
var things = {};
for (let i = 0; i < 3; i++) {
    let index = i;
    things["fun" + i] = function() {
        console.log(index);
    };
}

things["fun0"](); // prints 0
things["fun1"](); // prints 1
things["fun2"](); // prints 2

我使用 Traceur 和 node --harmony 测试了脚本.

I tested the script with Traceur and node --harmony.

推荐答案

squint 的回答不再是最新的.在 ECMA 6 规范, 指定的行为是在

squint's answer is no longer up-to-date. In ECMA 6 specification, the specified behaviour is that in

for(let i;;){}

i 为循环的每次迭代获取一个新的绑定.

i gets a new binding for every iteration of the loop.

这意味着每个闭包捕获一个不同的 i 实例.所以 012 的结果是目前正确的结果.当您在 Chrome v47+ 中运行它时,您会得到正确的结果.当您在 IE11 和 Edge 中运行它时,目前似乎产生了错误的结果 (333).

This means that every closure captures a different i instance. So the result of 012 is the correct result as of now. When you run this in Chrome v47+, you get the correct result. When you run it in IE11 and Edge, currently the incorrect result (333) seems to be produced.

有关此错误/功能的更多信息可以在 中的链接中找到本页;

More information regarding this bug/feature can be found in the links in this page;

自从使用 let 表达式后,每次迭代都会创建一个新的词法作用域,链接到前一个作用域.这对使用 let 表达式的性能有影响,报告为 此处.

Since when the let expression is used, every iteration creates a new lexical scope chained up to the previous scope. This has performance implications for using the let expression, which is reported here.

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

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