【问题标题】:Asyncronous variables outside a for loopfor 循环外的异步变量
【发布时间】:2013-04-04 16:33:33
【问题描述】:

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

【问题讨论】:

    标签: javascript ajax variables asynchronous for-loop


    【解决方案1】:

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

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

    改变这一行:

    getCount(result);
    

    到这里:

    var count = getCount(result);
    

    你应该没事的。 :)

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

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

    【讨论】:

      【解决方案2】:

      我不知道您为什么提到 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
      

      【讨论】:

        【解决方案3】:

        首先,您有一个额外的 = 符号,过度扩展了您的 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

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2017-05-19
          • 1970-01-01
          • 2020-04-21
          • 2016-05-06
          • 1970-01-01
          • 1970-01-01
          • 2015-04-11
          相关资源
          最近更新 更多