Javascript Var 和 Light 用法
Javascript Var and Let Usage
const array = [1, 2, 3, 4];
for (var index = 0; index < array.length; index++) {
setTimeout(() => {
console.log("I am at index " + index);
});
}
When I use the "var" keyword in the for loop I get the output
I am at index 4
I am at index 4
I am at index 4
I am at index 4
But When I use the "let" keyword in the for loop,
const array = [1, 2, 3, 4];
for (let index = 0; index < array.length; index++) {
setTimeout(() => {
console.log("I am at index " + index);
});
}
I am at index 0
I am at index 1
I am at index 2
I am at index 3
Can anyone tell me what's happening here?
你的问题的答案需要你理解
- Hoisting in JS
- Hoisting Diff in var and let type
- Scope Diff in var and let type
- Clousures
var
类型变量有一个 function/script
作用域,由于 hoisting
它的声明将移出 for 循环,所以它会进入 global scope
在每次迭代中,它都会发生变化,所有三个闭包将共享全局词法范围内的单个变量 i
,而如果我们将 var
替换为 let
那么它就不会移到外面for 循环是一个 block-scoped
,每次迭代都是一个新块,三个超时回调将有三个不同的词法范围和一个共享的全局范围(我们的代码中没有任何内容)。
const array = [1, 2, 3, 4];
for (var index = 0; index < array.length; index++) {
setTimeout(() => {
console.log("I am at index " + index);
});
}
When I use the "var" keyword in the for loop I get the output
I am at index 4
I am at index 4
I am at index 4
I am at index 4
But When I use the "let" keyword in the for loop,
const array = [1, 2, 3, 4];
for (let index = 0; index < array.length; index++) {
setTimeout(() => {
console.log("I am at index " + index);
});
}
I am at index 0
I am at index 1
I am at index 2
I am at index 3
Can anyone tell me what's happening here?
你的问题的答案需要你理解
- Hoisting in JS
- Hoisting Diff in var and let type
- Scope Diff in var and let type
- Clousures
var
类型变量有一个 function/script
作用域,由于 hoisting
它的声明将移出 for 循环,所以它会进入 global scope
在每次迭代中,它都会发生变化,所有三个闭包将共享全局词法范围内的单个变量 i
,而如果我们将 var
替换为 let
那么它就不会移到外面for 循环是一个 block-scoped
,每次迭代都是一个新块,三个超时回调将有三个不同的词法范围和一个共享的全局范围(我们的代码中没有任何内容)。