循环内部的函数-如何正确执行

Functions inside for loops - how to do it right?

本文关键字:何正确 执行 函数 内部 循环      更新时间:2023-09-26

我很难理解javascript的功能,我将用这段代码来解释它(假设patients大小为3):

for(j=0; j<patients.length; j++){
            console.log("before function - "+j);
            DButils.getDaysLeft(patients[j] , function(daysLeft){
                console.log("inside function - "+j);
            });
            console.log("end - "+j);
        }

这是我得到的输出:

before function - 0
end - 0
before function - 1
end - 1
before function - 2
end - 2
inside function - 3
inside function - 3
inside function - 3

因为这个问题,如果我在函数内做patients[j],它总是给我undefined,显然是因为患者只有3的大小。

我知道函数是一个线程,因此在我们进入函数的回调之前循环就结束了,但我该如何解决它呢?我能做些什么让它像c#java那样作为一个正常的"for循环"来工作?

JavaScript具有function级作用域,而不是block级作用域。

使用closure,它会记住创建它的变量的值。

试试这个:

for (j = 0; j < patients.length; j++) {
  console.log("before function - " + j);
  DButils.getDaysLeft(patients[j], (function(j) {
    return function(daysLeft) {
      console.log("inside function - " + j);
    }
  })(j));
  console.log("end - " + j);
}