关于 “let” 如何与循环结合的方式感到困惑。

huangapple go评论64阅读模式
英文:

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).

huangapple
  • 本文由 发表于 2023年3月9日 16:45:17
  • 转载请务必保留本文链接:https://go.coder-hub.com/75682200.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定