箭头功能捕获策略,以使声明变量

发布于 2025-02-05 23:49:47 字数 676 浏览 0 评论 0原文

我一直在阅读乔恩·斯基特(Jon Skeet)的文章 关于封闭策略,并希望与JavaScript探索情况。

arr = [];
for(let i = 0; i < 3; i++) {
    arr.push(() => console.log(i));
}
arr.forEach(ele => ele());



arr = [];
let j;
for(j = 0; j < 3; j++) {
    arr.push(() => console.log(j));
}
arr.forEach(ele => ele());

令人惊讶的是,第一个打印0,1,2和第二个3,3,3

我还发现 that JS总是捕获变量。那为什么第一种情况呢?

I've been reading Jon Skeet's article on closure capturing strategies and want to explore what's the case with JavaScript.

arr = [];
for(let i = 0; i < 3; i++) {
    arr.push(() => console.log(i));
}
arr.forEach(ele => ele());



arr = [];
let j;
for(j = 0; j < 3; j++) {
    arr.push(() => console.log(j));
}
arr.forEach(ele => ele());

Surprisingly, the first prints 0,1,2 and the second 3,3,3.

I also found that JS always captures variables. So why the first case?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

世态炎凉 2025-02-12 23:49:47
arr = [];
for(let i = 0; i < 3; i++) {
    arr.push(() => console.log('1', i));
}
arr.forEach(ele => ele());



arr = [];
let k;
for(k = 0; k < 3; k++) {
    arr.push(() => console.log('2', k));
}
arr.forEach(ele => ele());

我已经在控制台内添加了字符串1和2。

第一个结束是1,它可以按预期工作,因为LET关键字范围范围为for循环。另一方面,第二个循环中的console.log将scoppep的k取在窗口范围中,因此当console.log运行时,k的值将设置为for循环的末端的k值, i的值仅有效,并且在第一个循环内部范围内(因此是闭合)。

arr = [];
for(let i = 0; i < 3; i++) {
    arr.push(() => console.log('1', i));
}
arr.forEach(ele => ele());



arr = [];
let k;
for(k = 0; k < 3; k++) {
    arr.push(() => console.log('2', k));
}
arr.forEach(ele => ele());

I've added the strings 1 and 2 inside the console.logs so that you can better see which one is actually going first.

The first to end is 1 and it works as expected because the let keyword is scoped to the for loop. On the other hand, console.log in the second loop takes k which is scoped in the window scope, thus when console.log runs, the value of k is going to be set to that of the end of the for loop, while the value of i is only valid and scoped (thus the closure) inside the first for loop.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文