0

私はAJAXを使い始めたばかりで、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;
4

3 に答える 3

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 に答える