让...的范围界定 [英] Block scoping of let and for…of

查看:100
本文介绍了让...的范围界定的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

let 在ES2015中的语句允许我们声明块范围变量,以便例如下面的代码可以做到:

The let statement in ES2015 allows us to declare block scope variables, so that for example the following code does what we want:

let fs = [];
for (let i = 0; i < 3; i++) {
    fs.push(() => i);
}
console.log(fs.map(f => f())); // 0, 1, 2

但是,它似乎在Firefox 与 for ... of 循环,迭代迭代对象。这里,块范围被忽略,我们得到的结果就好像我们使用 var 而不是:

However, it does not seem to work in Firefox with the for…of loop which iterates over iterable objects. Here, the block scope is ignored, and we get the same result as if we used var instead:

fs = [];
let nums = [0, 1, 2];
for (let i of nums) {
    fs.push(() => i);
}
console.log(fs.map(f => f())); // 2, 2, 2

为什么 let 不在这里工作,而且内部的内容与 ...的循环有什么区别?

Why is the behavior of let not working here, and what’s internally so different about the for…of loop that this breaks?

推荐答案

正如其他人在评论中指出的那样,这种破坏的行为似乎是Firefox特有的,代码在其他环境(例如V8 / Node)中正常工作。

As others pointed out in the comments, this broken behavior seems to be specific to Firefox, and the code is working properly in other environments (e.g. V8/Node).

因此,我已经创建了一个错误报告为它我会从Firefox团队了解到新的内容,我会更新这个答案。

As such, I have created a bug report for it. I’ll update this answer as I learn something new from the Firefox team.

并已经登陆中央代码库。该修复程序现已包含在 Firefox 51版本中它的最终版本是在2017年1月24日。

This bug has been fixed around August last year and has since landed in the central codebase. The fix is now included in the Firefox 51 release that had its final release on January 24th, 2017.

我正在使用Firefox Nightly预览版本,并在一段时间内正常工作。

I’m using the Firefox Nightly preview versions and it has been working there properly for a while.

这篇关于让...的范围界定的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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