为什么此代码返回未定义的4次而不是数组值

Why does this code return undefined 4 times instead of the array values?

本文关键字:数组 4次 代码 返回 未定义 为什么      更新时间:2023-09-26

这是Avaylo Gerchev关于IIFE的博客文章中的一个例子。以下代码块按设计返回4个重复的"未定义"响应:

function printFruits(fruits){
  for (var i = 0; i < fruits.length; i++) {
   setTimeout( function(){
      console.log( fruits[i] );
    }, i * 1000 );
  }
}
printFruits(["Lemon", "Orange", "Mango", "Banana"]);

Avaylo随后展示了如何产生(对我来说)第一个代码块的预期输出(它输出数组的值):

function printFruits(fruits){
  for (var i = 0; i < fruits.length; i++) {
    (function(){
      var current = i;                    // define new variable that will hold the current value of "i"
      setTimeout( function(){
        console.log( fruits[current] );   // this time the value of "current" will be different for each iteration
      }, current * 1000 );
    })();
  }
}
printFruits(["Lemon", "Orange", "Mango", "Banana"]);

我知道IIFE创建了一个新的范围。我不明白的是,为什么第一块代码没有产生(对我来说)返回数组中值的预期输出。我已经盯着这个看了几天了,因此我得出结论,我的javascript知识缺少一些基本的东西。

感谢您的真知灼见!

在第一个代码块中,闭包无法访问变量"i",因为setTimeout只定义了要运行的代码,但并没有在定义时实际运行,只是在以后。

在那里有闭包并立即运行它(末尾用括号())是在每次迭代中保存"i"值的一种方法,这样当setTimeout运行时,它就可以访问它。