在for循环中放入关键字 [英] let keyword in the for loop

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

问题描述

ECMAScript 6的 let 应该提供块范围,而不会引起头痛。有些可以解释为什么在代码下面的 i 在函数中解析为循环中的最后一个值(就像使用 var )而不是当前迭代中的值?

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

东西[fun0](); //打印3
东西[fun1](); //打印3
东西[fun2](); //打印3

根据 let 在中的 MDN >循环就像在循环体的范围内绑定变量。当我在块内使用一个临时变量时,事情正如我所期待的那样工作。为什么这是必要的?

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

东西[fun0](); // print 0
things [fun1](); //打印1
东西[fun2](); //打印2

我用Traceur和节点 - 和谐测试了脚本

解决方案

squint的答案不再是最新的。在 ECMA 6规格 ,指定的行为是在

  for(let i ;;){} 

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



这意味着每个闭包都捕获不同的 i 实例。因此, 012 的结果是现在的正确结果。当您在Chrome v47 +中运行时,您会得到正确的结果。当您在IE11和Edge中运行它时,目前正在生成错误的结果( 333 )。



更多有关此错误/功能的信息可以在此页;



由于使用 let 表达式时,每次迭代都会创建一个新的词法作用域,以前的范围。这对于使用 let 表达式而言具有性能意义,该表达式被报告为 here


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

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

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

解决方案

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

for(let i;;){}

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

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;

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循环中放入关键字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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