2

我有一个变量如下:

var dataset = {
"towns": [
    ["Aladağ", "Adana", [35.4,37.5], [0]],
    ["Ceyhan", "Adana", [35.8,37], [0]],
    ["Feke", "Adana", [35.9,37.8], [0]]
    ]
};

该变量中有很多城镇数据。如何有效地从数据中提取第三个元素的第一个元素?我,e,...下面会是什么?

var myArray = ...
//myArray == [35.4,35.8,35.9] for the given data 

如果我想将两个值都存储在数组中该怎么办?那是

var myArray = ...
//myArray == [[35.4,37.5], [35.8,37], [35.9,37.8]] for the given data 

我对 Javascript 很陌生。我希望有一种不使用 for 循环的方法。

4

2 回答 2

8

在较新的浏览器上,您可以使用map, 或者forEach避免使用for循环。

var myArray = dataset.towns.map(function(town){
  return town[2];
});
// myArray == [[35.4,37.5], [35.8,37], [35.9,37.8]]

但是 for 循环更兼容。

var myArray = [];
for(var i = 0, len = dataset.towns.length; i < len; i++){
  myArray.push(dataset.towns[i][2];
}
于 2012-12-29T16:16:49.167 回答
2

没有循环是不可能的:

var myArray = [];
for (var i = 0; i < dataset.towns.length; i++) {
    myArray.push(dataset.towns[i][2][0]);
}
// at this stage myArray = [35.4, 35.8, 35.9]

如果我想将两个值都存储在数组中该怎么办?

类似地,您只需添加整个数组,而不仅仅是第一个元素:

var myArray = [];
for (var i = 0; i < dataset.towns.length; i++) {
    myArray.push(dataset.towns[i][2]);
}
// at this stage myArray = [[35.4,37.5], [35.8,37], [35.9,37.8]]
于 2012-12-29T16:17:00.757 回答