我剛剛開始使用AJAX,並試圖在for循環中設置一個變量。然後我想稍後調用該變量並使用它的值。for循環之外的異步變量
當然,這是同步的,需要腳本停止執行才能在返回函數的新值之前運行循環。
我希望有人知道更好的方式來獲得for循環後的值for循環已經運行並在之後直接在我的代碼中使用它。
我不希望使用setTimeout()
黑客繞過這個問題(畢竟它是一個黑客)。
var getCount = function getCount(res) {
count = { active: 0, closed: 0 }; //Variable defined here
for(i=0; i<=res.length; i++) {
if(res[i].status == 'active') {
count.active ++;
} else { count.closed ++; }
}
return count; //And returned here
};
getCount(result);
console.log(count); //Here's where I need the result of the for loop
//Currently this outputs the count object with both properties set to 0;
很好的反饋!非常感謝,修復它。 – Websmith 2013-04-04 17:14:49