为什么 const 在 JavaScript 的某些 for 循环中起作用? [英] Why does const work in some for-loops in JavaScript?
问题描述
我确实知道为什么 const
在 for 循环中不起作用.我们需要创建一个新的作用域并将一个值复制到其中.所以这不会飞.
I do know why const
doesn't work in for-loops. We need to create a new scope and copy over a value into that. So this won't fly.
for(const i = 0; i < 5; i++) console.log(i);
然而这会.
for(let i = 0; i < 5; i++) console.log(i);
但是,我注意到它们在循环处理像这样的对象的属性时都可以工作.
However, I noticed that both of them work when looping though the properties of an object like this.
for(let property in thingy) console.log(property);
for(const property in thingy) console.log(property);
我不知道为什么.
推荐答案
for (const property in object)
之所以有效,是因为每次迭代都会得到一个新变量,该变量的作用域仅限于该迭代.您可以通过在循环内使用闭包轻松检查:
for (const property in object)
works because with each iteration you get a new variable, which is scoped only to that iteration. You can easily check that by using a closure inside a loop:
for (const property in {a: 1, b: 2}) {
setTimeout(() => {
console.log(property);
}, 100);
}
这会记录a
和b
,但是如果您将const
更改为var
,则会记录b
两次.
This logs a
and b
, but if you change const
to var
, it logs b
twice.
这篇关于为什么 const 在 JavaScript 的某些 for 循环中起作用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!