我有一個很艱難的時期與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
可以使用這段代碼?
歡迎JS。你一定很困惑。將'function(daysLeft){console.log(「inside function - 」+ j)}'函數定義爲一個IIFE並將'j'保存在閉包下。像'(function(daysLeft){console.log(「inside function - 」+ j)})(j);' – Redu