javascript - How to understand "the loop statement part is a parent scope, and the inside of the loop body is a separate child scope"?
PHPz
PHPz 2017-05-18 10:52:55
0
5
468

如题。

for (var i = 0; i < 3; i++) {
  var i = 'abc';
  console.log(i);
}
//为什么这里只输出一次 abc ? 是因为'abc'++ <3 是false吗?
for (let i = 0; i < 3; i++) {
  let i = 'abc';
  console.log(i);
}//为什么是3次 abc?

for (let i = 0; i < 3; i ) {

console.log(i) //这里报ReferenceError: i is not define?是因为暂时性死区?
let i = 'abc';

}

PHPz
PHPz

学习是最好的投资!

reply all(5)
我想大声告诉你

First one, you are herefor里面var i,它们是在同一个作用域的,因为var是一个函数作用域。i = 'abc';i++,这样i就变成NaN了。NaN和数字比较,无论是什么比较,都为false. So, only output once.

The second one is valid in the let是块级作用域,所以在for (let i = 0; ...)定义的i只在for的括号里有效,在块内是没有效果的,所以let i = 'abc'是相当于重新定义了一个变量,是for代码块的块级作用域的变量,只在forcode block. So it was executed three times.

The third question, you console.log之后定义了let i,所以idid not define it when you called it. See the above item.

迷茫

Because the variables are improved

In the first one, the outer i is changed to 'abc', so it exits directly, while in the second one, 'abc' is restricted to the block-level scope of for and will not change.

Peter_Zhu

When using var declaration
for(var i=0; i<3; i++){} is equivalent to var i;for(i=0;i<3;i++){}.
It’s more obvious when you look at it this way
The first piece of code loops once because:

你在内部将i赋值为字符串,无法进行++操作,for循环只运行了一次就结束了。

The variables declared by let in the second piece of code only take effect in the block-level scope where they are located. In the above code, () and {} are two block-level scopes. They do not affect each other. The definition within {} i will not affect the i declared in ()

世界只因有你

var is function scope. In the second loop judgment, i = 'abc'; , 而'abc'++ < 3 is false, so the first for loop is only executed once.

let is block-level scope. Every time the for loop redefines an i, the scope of let i = 'abc' is within the loop body and will not affect the loop body.

曾经蜡笔没有小新

Reference here: http://www.ecma-international...

When the first part of for is var (VariableDeclarationList), the declared variables will be merged into the function scope, just like they were declared separately.

When the first part of for is let, the loop will be divided into oldEnv and loopEnv. loopEnv can be regarded as an intermediate layer sandwiched between the loop body and the outside of the loop, so it is not affected.

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template