2013-04-04 139 views
0

我剛剛開始使用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; 

回答

2

我不確定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

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 
+0

感謝您的幫助巴特 – Websmith 2013-04-04 17:01:18

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 
} 

here