Why JavaScript const works well with for in loop [duplicate]

南笙酒味 提交于 2019-12-11 05:32:55

问题


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?

For in with let

for (let num in nums) {
    console.log(num); // works well, as usual
}

For in with const

for (const num in nums) {
    console.log(num); // why const value getting replaced
}

回答1:


Why JavaScript const works same as let in for in loop?

By definition, const is block scoped like let.

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.




回答2:


Why the const num value getting updated in each iteration of the for in?

It isn't getting updated. Similar to let, it is scoped to the loop block and creates a new const variable on every iteration, initialised with the respective property key.




回答3:


Maybe (not sure) is for the scope in which it's declared. It seems you are declaring the constant in the scope of the for statement, so it gets removed and redeclared every new iteration. So each time it has a different value.

It's a guess, not sure...



来源:https://stackoverflow.com/questions/46932731/why-javascript-const-works-well-with-for-in-loop

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!