我能够使用下面的代码成功检索我的JSON对象。当我记录变量“ value2”时,可以在控制台中看到这些值。但是,我无法用value2填充“ arraytest”。函数运行后,在控制台中打印arraytest的值时,数组为空。

    var accessURL = "https://lots-of-holes.firebaseio.com/.json";
    var arraytest= [];
    i=0;
    $.getJSON(accessURL, function(data){
    $.each(data, function (index, value) {
        $.each(value, function (index2, value2) {
                arraytest[i++] = value2;
                console.log(value2);
        });
      });
    });
    console.log(arraytest);


这可能与查询运行速度比我的JavaScript慢有关,但我不确定如何处理。如果您认为还有其他问题,并且仍然希望提供帮助,请给我发消息,我会给您一个指向我的源代码的链接。我是javascript和ajax的新手。

JSON如下:

{"-37 932570096604465 * 101 68831543328787":{"frequency":2.0,"lat":-37.932570096604465,"lon":101.68831543328787},"-79 14830348215878 * -147 67984075199726":{"frequency":2.0,"lat":-79.14830348215878,"lon":-147.67984075199726},"-9 566696357885519 * -86 19132124619011":{"frequency":2.0,"lat":-9.566696357885519,"lon":-86.19132124619011},"23 175286370699936 * -14 694988385655307":{"frequency":2.0,"lat":23.175286370699936,"lon":-14.694988385655307},"25 686572941892038 * -54 7326350327119":{"frequency":2.0,"lat":25.686572941892038,"lon":-54.7326350327119},"39 2538061 * -76 7143967":{"frequency":10.0,"lat":39.2538061,"lon":-76.7143967},"39 2538512 * -76 7144418":{"frequency":2.0,"lat":39.2538512,"lon":-76.7144418},"39 2543882 * -76 7132241":{"frequency":2.0,"lat":39.2543882,"lon":-76.7132241},"39 2543986 * -76 7133143":{"frequency":2.0,"lat":39.2543986,"lon":-76.7133143},"52 0353479004271 * 147 31906570837452":{"frequency":2.0,"lat":52.0353479004271,"lon":147.31906570837452},"7 568992516106547 * 37 95350231539729":{"frequency":2.0,"lat":7.568992516106547,"lon":37.95350231539729},"78 51991220059591 * 69 61956909362064":{"frequency":2.0,"lat":78.51991220059591,"lon":69.61956909362064}}

最佳答案

$.getJSON是一个异步函数。因此console.log(arraytest)在运行arraytest之前正在运行。

您可以尝试以下方法:

    var accessURL = "https://lots-of-holes.firebaseio.com/.json";
    var arraytest= [];
    i=0;
    $.getJSON(accessURL, function(data){
    $.each(data, function (index, value) {
        $.each(value, function (index2, value2) {
                arraytest[i++] = value2;
                console.log(value2);
        });
      });
    console.log(arraytest);
    });

10-01 08:23