为什么JavaScript const可以在for循环中很好地工作 [英] Why JavaScript const works well with for in loop
问题描述
为什么JavaScript const
在for in
循环中与let
相同? const
用于在EC6中声明常量.那么为什么const num
的值在for in
的每次迭代中都会更新?
Why JavaScript const
works same as let
in for in
loop? const
is using to declare constants in EC6. Then why the const num
value getting updated in each iteration of the for in
?
与let配合使用
for (let num in nums) {
console.log(num); // works well, as usual
}
用于const
for (const num in nums) {
console.log(num); // why const value getting replaced
}
推荐答案
为什么JavaScript const的作用与让in for in循环相同?
Why JavaScript const works same as let in for in loop?
根据定义,const
的作用域类似于let
.
By definition, const
is block scoped like let
.
那为什么在for in的每次迭代中都会更新const num值?
Then why the const num value getting updated in each iteration of the for in?
不是.由于它是块作用域的,因此每次循环时,旧常量都会超出作用域,并创建一个新的常量.
It isn't. Since it is block scoped, each time you go around the loop the old constant drops out of scope and you create a new one.
这篇关于为什么JavaScript const可以在for循环中很好地工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!