如题。
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';
}
First one, you are here
for
里面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
代码块的块级作用域的变量,只在for
code block. So it was executed three times.The third question, you
console.log
之后定义了let i
,所以i
did 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.
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:
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.