简体   繁体   English

如何将数组推入Javascript数组中?

[英]How to push an array into an array in Javascript?

I have 2 arrays in JS that holds values of longitudes and latitudes. 我在JS中有2个数组,其中包含经度和纬度的值。 I want to create dynamic variable locations which holds data corresponding to these arrays. 我想创建动态变量位置,以保存与这些数组相对应的数据。 Note that the size of these arrays changes each time (depending on the user). 请注意,这些数组的大小每次都会更改(取决于用户)。

Arrays that I want to push into locations array: 我想推入位置数组的数组:

  • longi_array holds all longitude values longi_array保存所有经度值
  • lati_array holds all latitude values lati_array保存所有纬度值

Now, I'm trying to create a dynamic variable locations (which is an array of arrays) the size of which depends on how many elements are currently in latitude and longitude arrays. 现在,我试图创建一个动态变量位置(它是一个数组数组),其大小取决于当前在纬度和经度数组中的元素数量。

This is my code: 这是我的代码:

var locations = [];
for (var i = 0; i < lati_array.length; i++) { 

      locations.push(['<h4>Some Beach</h4>', lati_array[i], longi_array[i]]);
  });

This is not working. 这是行不通的。 I do not get an error message. 我没有收到错误消息。 Netbeans does not show any syntax errors. Netbeans不显示任何语法错误。 The behavior that I was expecting was that locations was supposed to now hold an array of arrays that would help me plot place markers on Google maps. 我期望的行为是位置现在应该包含一个数组数组,这将有助于我在Google地图上绘制位置标记。 It works if I insert each array value manually into the locations array, but when I try to do it dynamically, the google maps doesn't show up at all -- which means there's something wrong with locations array. 如果我将每个数组值手动插入到locations数组中,它将起作用,但是当我尝试动态执行此操作时,google maps根本不会显示-这意味着locations数组存在问题。

It seems like I'm making some mistake while trying to push the array into the location array. 似乎在尝试将数组推入位置数组时犯了一些错误。 What am I doing wrong? 我究竟做错了什么?

Try to replace }); 尝试替换}); by } and it work : 通过} ,它可以工作:

Hope this helps. 希望这可以帮助。

 var locations = []; var lati_array = [1,2,3,4,5]; var longi_array = [11,22,33,44,55]; for (var i = 0; i < lati_array.length; i++) { locations.push(['<h4>Some Beach</h4>', lati_array[i], longi_array[i]]); } console.log(locations); //Output : [Array[3], Array[3], Array[3], Array[3], Array[3]] 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM