2016-03-25 58 views
0

我有一個很艱難的時期與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可以使用這段代碼?

+0

歡迎JS。你一定很困惑。將'function(daysLeft){console.log(「inside function - 」+ j)}'函數定義爲一個IIFE並將'j'保存在閉包下。像'(function(daysLeft){console.log(「inside function - 」+ j)})(j);' – Redu

回答

2

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

+0

我應該編輯「getDaysLeft」簽名以使其工作嗎? –

+0

No..Closure返回內部函數,這將是您的回調函數,稍後會在您的回調函數正在工作時調用... – Rayon

+0

謝謝,它的工作原理,我會盡快答覆。 –