将数组推入 Javascript (jQuery) 中的数组

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13831037/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 19:54:03  来源:igfitidea点击:

Push array into array in Javascript (jQuery)

javascriptjqueryarrayspushmultidimensional-array

提问by rodd

I've been trying to get the push() method on a loop to build a structure as follows:

我一直在尝试在循环中使用 push() 方法来构建如下结构:

var locations2 = [
    ['User', position.coords.latitude, position.coords.longitude, 1],
    ['Bondi Beach', -33.890542, 151.274856, 2],
    ['Coogee Beach', -33.923036, 151.259052, 3],
    ['Cronulla Beach', -34.028249, 151.157507, 4],
    ['Manly Beach', -33.80010128657071, 151.28747820854187, 5],
    ['Maroubra Beach', -33.950198, 151.259302, 6]
];

This is my code:

这是我的代码:

var locations = [];

$.ajax({
    type: "POST",
    url: "/ajax/map.php",
    data: "name=test",
    dataType: "json",
    cache: false,
    success: function(data){
        $.each(data.points, function(i,item){
            array_push = ["test", parseFloat(item.origem_lat), parseFloat(item.origem_lng), i];
            locations.push(array_push);
        });               
    }
});  

However, the Javascript console.log for locations shows an empty array.

但是,位置的 Javascript console.log 显示一个空数组。

I have tried to use push() in many different ways, but I cannot get the same structure as locations2. The biggest problem here is that I do not know how many arrays are going to be inside the locations array before the loop, so I can't initialize it beforehand.

我尝试以多种不同的方式使用 push(),但无法获得与locations2 相同的结构。这里最大的问题是我不知道在循环之前位置数组中有多少个数组,所以我不能事先初始化它。

Any thoughts?

有什么想法吗?

采纳答案by rodd

I figured out what the problem is. It has nothing to do with the push() method itself. Apparently ajax calls are not executed in sequential order (that's the reason it's asynchronous). I added async: falsein the ajax call options and now everything works perfectly.

我想出了问题所在。它与 push() 方法本身无关。显然 ajax 调用不是按顺序执行的(这就是它异步的原因)。我在 ajax 调用选项中添加了async: false,现在一切正常。

Thanks everyone for the input.

感谢大家的投入。