简体   繁体   中英

How to push an array into an array in Javascript?

I have 2 arrays in JS that holds values of longitudes and latitudes. 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
  • lati_array holds all latitude values

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. 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. 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.

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]] 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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