for循环之外的异步变量

问题描述:

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

我不确定AJAX与您的问题有什么关系。

您不会将getCount函数的结果赋值给count变量(除非您希望count变量是全局变量,但在这种情况下,您需要在getCount函数定义之前定义它)。

改变这一行:

getCount(result); 

这样:

var count = getCount(result); 

你应该是好的。 :)

我也会建议,当声明变量时,总是用var声明它们。在你的情况下:

var count = { active: 0, closed: 0}; 
+0

很好的反馈!非常感谢,修复它。 – Websmith 2013-04-04 17:14:49

我不知道你为什么提到AJAX,因为你的代码没有任何异步。 从我在你的例子中看到的东西,我没有看到所有的困难。

只要使用它作为任何其他功能。

function getCount(res) { 
    var 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 
}; 

console.log(getCount(result)); //Here's where I need the result of the for loop 
+0

感谢您的帮助巴特 – Websmith 2013-04-04 17:01:18

首先,你有一个额外的=迹象,这是过度延长您for循环。我不知道这是否回答你的问题,异步,但这里是我会怎么做:

// sample object 
var result = [ 
    {status:"active"}, 
    {status:"not-active"}, 
    {status:"active"} 
]; 

// kick off the function to get the count object back 
var counts = getCount(result); 

console.log(counts); 


function getCount(res) { 
    var count = { active: 0, closed: 0 }; //Variable defined here, make sure you have var to keep it from going global scope 

    for(i=0; i<res.length; i++) { //here you had a wrong "=" 
     if(res[i].status === 'active') { 
      count.active ++; 
     } else { count.closed ++; } 
    } 
    return count; //And returned here 
} 

here