JavaScript 中的 let 与 var [重复]

2023-12-23

我知道 let 具有块作用域,var 具有函数作用域。但我不明白在这种情况下,如何使用 let 来解决问题

const arr = [1,2,3,4];
for (var i = 0; i < arr.length; i++) {
setTimeout(function() {
   console.log(arr[i]) 
}, 1000);
} // Prints undefined 5 times

const arr = [1,2,3,4];
for (let i = 0; i < arr.length; i++) {
setTimeout(function() {
   console.log(arr[i]) 
}, 1000);
} // Prints all the values correctly

这都与变量的作用域有关。让我们尝试将这两部分包装到函数中,并观察输出:

function test() {
  // `i` will be declared here, making it a non-for-loop scoped variable
  const arr = [1, 2, 3, 4];
  for (var i = 0; i < arr.length; i++) {
    setTimeout(function() {
      console.log(arr[i])
    }, 1000);
  } // Prints undefined 5 times
}

test();

所以在第一种情况下,i将被提升,并且由于异步特性setTimeout, i当循环结束时,将立即变为 4,无需等待。这将使arr[i]指向一个undefined数组中的元素。

在第二种情况下,i没有被提升,并且具有对循环的每个迭代的范围访问,使得i准确地可用于console.log陈述。因此结果符合预期:

function test() {
  const arr = [1, 2, 3, 4];
  for (let i = 0; i < arr.length; i++) {
    setTimeout(function() {
      console.log(arr[i])
    }, 1000);
  } // Prints all the values correctly

}

test();
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

JavaScript 中的 let 与 var [重复] 的相关文章

随机推荐