【问题标题】:Functions inside for loops - how to do it right? [duplicate]for 循环中的函数 - 如何正确执行? [复制]
【发布时间】:2016-03-25 11:48:22
【问题描述】:

我很难使用 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 循环”与那段代码一起工作?

【问题讨论】:

  • 欢迎来到 JS。你一定很困惑。将function(daysLeft){console.log("inside function - "+j)} 函数定义设为IIFE,并将j 保存在闭包下。喜欢(function(daysLeft){console.log("inside function - "+j)})(j);

标签: javascript


【解决方案1】:

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);
}

【讨论】:

  • 我应该编辑“getDaysLeft”签名以使其工作吗?
  • No..Closure 返回内部函数,这将是您的回调,稍后将在您的回调工作时调用它......
  • 谢谢,它正在工作,我会尽快标记为答案。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2022-11-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多