简体   繁体   English

使用for循环创建数组的数组

[英]Create an array of arrays using for loop

My goal is to create an array that look something like this 我的目标是创建一个看起来像这样的数组

var locations = [
    [
        "New Mermaid",
        36.9079,
        -76.199
    ],
    [
        "1950 Fish Dish",
        36.87224,
        -76.29518
    ]
]; 

I've tried 我试过了

var data = $locations;
var locations = [];

for (i = 0; i < data.length; i++) {

  locations[i] =
  data[i]['name']+','+
  data[i]['lat']+','+
  data[i]['lng'];

}

console.log(locations);

I've got 我有

["Apple  HQ,33.0241101,39.5865834", "Google MA,43.9315743,20.2366877"]

However that is not the exact format. 但是,这不是确切的格式。


I want 我想要

var locations = [
    [
        "New Mermaid",
        36.9079,
        -76.199
    ],
    [
        "1950 Fish Dish",
        36.87224,
        -76.29518
    ]
];

How do I update my JS to get something like that ? 如何更新我的JS以获得类似的信息?

To build an "Array of arrays", this is one (of a few different methods): 要构建“数组数组”,这是(几种不同方法中的一种):

for (i = 0; i < data.length; i++) {
  locations[i] = [];
  locations[i][0] = data[i]['name'];
  locations[i][1] = data[i]['lat'];
  locations[i][2] = data[i]['lng'];
}

or 要么

for (i = 0; i < data.length; i++) {
  locations[i] = [data[i]['name'], data[i]['lat'], data[i]['lng']];
}
var locations = data.map(function(location){
  return [ location.name, location.lat, location.lng ];
}

Map will make an array with all the returned values from your function. Map将使用您的函数返回的所有值组成一个数组。 Each return will be an array consisting of the 3 attributes you are looking for. 每个返回将是一个包含您要查找的3个属性的数组。

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

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