为什么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属性)
之所以起作用,是因为每次迭代都会得到一个新变量,该变量的作用范围仅是该迭代.您可以通过在循环内使用闭包来轻松地进行检查:
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屋!