0

我刚开始使用 AJAX,我试图在 for 循环中设置一个变量。然后我想稍后调用该变量并使用它的值。

当然这将是同步的,需要脚本停止执行以便在返回函数的新值之前运行循环。

我希望有人知道在 for 循环运行后从 for 循环中获取值的更好方法,然后直接在我的代码中使用它。

我宁愿不使用setTimeout()hack 来绕过这个问题(毕竟这是一个 hack)。

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;
4

3 回答 3

2

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

您没有将 getCount 函数的结果分配给 count 变量(除非您打算将 count 变量设置为全局变量,但在这种情况下,您需要在 getCount 函数定义之前定义它)。

更改此行:

getCount(result);

对此:

var count = getCount(result);

你应该没事的。:)

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

var count = { active: 0, closed: 0};
于 2013-04-04T16:42:09.813 回答
0

我不知道你为什么提到 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
于 2013-04-04T16:42:47.070 回答
0

首先,你有一个额外的=标志,过度扩展了你的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
}

这里的例子。

于 2013-04-04T16:57:23.893 回答