在 p5.js 中遍历 JSON 数组

iterate though JSON array in p5.js

我有一台 return 的服务器:

我想遍历 p5.js

中的这些数据
var ms = []

function preload() {
  var url ='https://dest/url'
  ms = loadJSON(url)
}

我希望 return 一个数组,但它似乎 return 没有任何意义。

但是,如果我将相同的数据粘贴到 Javascript 控制台,我会得到不同的数据:

如何迭代此数据(它未作为数组加载)或将其转换为数组?

我想你是这个意思:

var array;
for (var key in ms) {
   if (!array) {
      array = [a[key]];
   } else {
      array.push(a[key]);
   }
}
console.log(array); // [ {'time': .... }, {...}, .. ]

您正在获取一个对象数组,这是您可以简单地迭代它们的方法

var data = [{"time":"12345","rate":"12345.12"},  {"time":"12345","rate":"12345.12"}, {"time":"12345","rate":"12345.12"}, {"time":"12345","rate":"12345.12"}, {"time":"12345","rate":"12345.12"} ];

for(obj of data){
  console.log("time and rate: ", obj.time, obj.rate)
}

正如其他人在评论中指出的那样,您所拥有的本质上是一个数组或一个类似数组的对象,更准确地说,这些可以很容易地转换为适当的数组,如下所示:

ms.length = Object.keys(ms).length;
var msArray = Array.prototype.slice.call(ms);

jettpleyn 的答案在 P5 中是唯一有效的。

但最终 - 我突然意识到我可以通过将从服务器返回的 JSON 更改为包含数组而不是直接包含数组的对象来让我的生活更轻松

{ "data":
[{"time":"85579.54189181328","rate":177.66287},{"time":"81978.61475682259","rate":177.66287},{"time":"78377.54175782204","rate":177.66287},{"time":"74776.58741879463","rate":177.66287},{"time":"71175.57481980324","rate":177.66287},{"time":"67574.59330582619","rate":177.66287},{"time":"63973.427922964096","rate":177.66287},{"time":"60372.39295697212","rate":177.66287},{"time":"56771.37366294861","rate":177.66287},{"time":"53170.276379823685","rate":177.66287},{"time":"49569.180530786514","rate":177.66287},{"time":"45968.02240085602","rate":177.66287},{"time":"42365.825628995895","rate":177.66287},{"time":"38764.64792180061","rate":177.71416},{"time":"35163.241872787476","rate":177.71416},{"time":"31562.00651884079","rate":177.72556},{"time":"27960.898827791214","rate":177.73126},{"time":"24359.687824964523","rate":177.67998},{"time":"20758.03328180313","rate":177.67998},{"time":"17156.808887004852","rate":174.53839},{"time":"13555.605601787567","rate":174.9276},{"time":"9954.546007871628","rate":175.35431},{"time":"6353.40945982933","rate":175.96582},{"time":"2752.3464789390564","rate":175.84541}]
}