javascript - 简单 JSON 调用的 console.log() 错误行为

标签 javascript html arrays json console.log

我初始化数组historyData=[0,0,...,0],然后处理一些JSON 文件并用结果填充数组。 Console.log-ing 数组内容给出 [0,0,...,0]。 但是如果我从 firebug 控制台运行 console.log(historicalData) ,我会得到正确的内容。为什么?

   var d = new Date();
   var m = d.getMonth();
   var y = d.getYear() +1900;
   var y2 = y-1;
   var historicalData=[0,0,0,0,0,0,0,0,0,0,0,0];    //init step
   var counter = 11;
   var i;

   for (i = m; i!= m || y!=y2; i--) {
    if (i==0) {
     i=12;
     y = y-1;
    }
    var src = "http://192.168.183.135/incidents/affectedUsersJSON.php?month=".concat(i).concat("&year=").concat(y);;
    (function (i,counter,historicalData) {
     $.getJSON(src, function funct(data) {
      count = Object.keys(data).length;
      if (count ==1 ) {
        historicalData[counter] = 0         //filling the array
      }
      else {
       historicalData[counter] = count;     //filling the array
      }
      counter = counter-1;
     })
    }(i,counter,historicalData));
   counter = counter-1;
   }
  </script>
</head>

<body>
<div id="users">Users</div>
  <script type="text/javascript">
    console.log(historicalData);            //console.log-ing the results: I get only ZEROS!
  </script>
</body>
</html>

对控制台中的输出感到失望后,我从控制台本身运行“console.log(historicalData)”并且..我得到了正确的结果。 为什么?

最佳答案

我相信 JSON 调用尚未完全返回。您需要设置回调

.done(function( data ) {

将 console.log 调用放在此处的结果上,您应该会得到您期望的结果。

给你引用

http://api.jquery.com/jquery.getjson/

关于javascript - 简单 JSON 调用的 console.log() 错误行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31922623/

相关文章:

javascript - 使用 PHP 数组和 JS 将值填充到下拉列表中

javascript - 首页加载时从 div 检索到的尺寸错误

php - 使用 PHP 在 mysql 数据库中进行数组搜索

c - C中如何让用户指定多维数组的大小

javascript - 我有办法在 slickgrid 标题中垂直对齐文本

c - 对字符数组执行 'xor' sumcheck

javascript - 如何让输入框点击时生效?

javascript - ko.applybindings 不适用于动态 html 元素

javascript - Visual Studio Code 自动完成/IntelliSense 不适用于 JavaScript

javascript - 将图像转换为 base64,无需 Canvas