for循环中的函数 - 如何正确执行?

时间:2016-03-25 11:48:22

标签: javascript

我正忙着运行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循环”工作?

1 个答案:

答案 0 :(得分:2)

  

JavaScript的function级别范围不是block级别范围。

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

试试这个:

&#13;
&#13;
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);
}
&#13;
&#13;
&#13;

相关问题