英文:
confused about the way let reacts with loops
问题
const OBJ = {
MINNI : 79,
TONU : 34,
RITU : 23,
}
for(let a in OBJ)
console.log(a,OBJ[a])
for(e of "abhi")
console.log(e)
now let actually executes the blocked scooped variable from outside the bracket .. haven't we all have been told that let doesn't react to the under bracket variables ? without loops it will throw an error of variable being undefined .. let me know if you have the answer to this one as I am much confused with this one
I were expecting that let won't react to the variable which is block scoped and yes it doesn't usually but with loops it is executing the code which is under the block
英文:
const OBJ = {
MINNI : 79,
TONU : 34,
RITU : 23,
}
for(let a in OBJ)
console.log(a,OBJ[a])
for(e of "abhi")
console.log(e)
now let actually executes the blocked scooped variable from outside the bracket .. haven't we all have been told that let doesn't react to the under bracket variables ? without loops it will throw en error of variable being undefined .. let me know if you have answer of this one as i am much confused with this one
i were expecting that let won't react to the variable which is blocked scooped and yes it doesn't usually but with loops it is executing the code which is under the block
答案1
得分: 2
使用let
关键字在for-in
(或for
,或for-of
)循环中,变量的作用域是构成循环体的语句的作用域。在你的情况下,循环体是console.log(a,OBJ[a])
,所以a
在作用域内,可以正常使用。
你似乎认为作用域需要循环的主体是一个代码块,但实际上不需要。这个循环:
for(let a in OBJ)
console.log(a,OBJ[a])
和这个循环是一样的:
for(let a in OBJ) {
console.log(a,OBJ[a])
}
在a
的作用域方面(以及几乎所有其他方面)都是相同的。
英文:
When you use let
in a for-in
(or for
, or for-of
) loop, the scope of the variable is the scope of the statement that forms the loop body. In your case, the loop body is console.log(a,OBJ[a])
, so a
is in scope and there's no problem using it.
You seem to think that the scope requires a block as the body of the loop, but it doesn't. This loop:
for(let a in OBJ)
console.log(a,OBJ[a])
is the same as this loop:
for(let a in OBJ) {
console.log(a,OBJ[a])
}
in terms of the scope of a
(and in nearly all other ways).
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论