[英]How to extract values from an array of arrays in Javascript?
I have a variable as follows: 我有一个变量,如下所示:
var dataset = {
"towns": [
["Aladağ", "Adana", [35.4,37.5], [0]],
["Ceyhan", "Adana", [35.8,37], [0]],
["Feke", "Adana", [35.9,37.8], [0]]
]
};
The variable has a lot of town data in it. 该变量中包含许多城镇数据。 How can I extract the first elements of the third ones from the data efficiently? 如何有效地从数据中提取第三个元素? I,e, what will ...
be below? I,E,你会...
低于?
var myArray = ...
//myArray == [35.4,35.8,35.9] for the given data
And what to do if I want to store both values in the array? 如果要将两个值都存储在数组中怎么办? That is 那是
var myArray = ...
//myArray == [[35.4,37.5], [35.8,37], [35.9,37.8]] for the given data
I'm very new to Javascript. 我是Java的新手。 I hope there's a way without using for loops. 我希望有一种不使用for循环的方法。
On newer browsers, you can use map
, or forEach
which would avoid using a for
loop. 在较新的浏览器上,可以使用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]]
But for loops are more compatible. 但是for循环更兼容。
var myArray = [];
for(var i = 0, len = dataset.towns.length; i < len; i++){
myArray.push(dataset.towns[i][2];
}
Impossible without loops: 不可能没有循环:
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]
And what to do if I want to store both values in the array? 如果要将两个值都存储在数组中怎么办?
Similar, you just add the entire array, not only the first element: 类似地,您只需添加整个数组,而不仅是第一个元素:
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]]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.