问题
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 thefor 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