我刚刚开始使用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