简体   繁体   English

如果我使用 var 而不是 let in for 循环,为什么代码返回 undefined

[英]Why is the code returning undefined if I use var instead of let in for loop

Why does my code return undefined if I use var inside a for loop instead of let.如果我在 for 循环中使用 var 而不是 let,为什么我的代码返回 undefined。 I have attached the output for let and var below the code blocks.我已在代码块下方附加了 let 和 var 的输出。

const a = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];

for (let i = 0; i < 10; i++) {
  setTimeout(() => console.log(a[i]), 3000);
}

Output : [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]输出:[1、2、3、4、5、6、7、8、9、10]

var i = 0;
for (i = 0; i < 10; i++) {
  setTimeout(() => console.log(a[i]), 3000);
}

// Output : [undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined ] // 输出:[未定义,未定义,未定义,未定义,未定义,未定义,未定义,未定义,未定义,未定义]

Variables declared by var keyword are scoped to the immediate function body so its falls under the function scope.var关键字声明的变量的作用域是直接函数体,因此它属于函数作用域。 And let variables are scoped to the immediate enclosing block denoted by { } - the block scope.并且变量的范围限定为由 { } 表示的直接封闭块 - 块范围。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM