使用for循环创建数组数组

时间:2016-02-01 19:16:16

标签: javascript jquery json

我的目标是创建一个看起来像这样的数组

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

我试过

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);

我有

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

然而,这不是确切的格式。

我想要

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

如何更新我的JS以获得类似的东西?

2 个答案:

答案 0 :(得分:3)

要构建“数组数组”,这是一个(几种不同的方法):

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'];
}

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

答案 1 :(得分:3)

var locations = data.map(function(location){
  return [ location.name, location.lat, location.lng ];
}

Map将生成一个包含函数返回值的数组。每个返回都是一个由您正在寻找的3个属性组成的数组。