[英]Combine 2 arrays into a multidimensional array?
This is based on my last question. 这是基于我的上一个问题。
I have these arrays: 我有这些数组:
var array1 = new Array ("Pepsi", "Coke", "Juice", "Water");
var array2 = new Array ("35", "17", "21", "99");
And I want to combine them to form a multidimensional array like this: 我想将它们组合起来形成一个像这样的多维数组:
[
["Pepsi","35"]
["Coke", "17"]
["Juice","21"]
["Water","99"]
]
I tried this script: 我试过这个脚本:
Values=[];
for (i = 0; i < array1.length; i++) {
Values[i] = Array(array1[i], array2[i]);
}
But it gave a result like this (correct values, incorrect names): 但它给出了这样的结果(正确的值,不正确的名称):
[
["a","35"]
["c","17"]
["E","21"]
["I","99"]
]
var array1 = ["Pepsi", "Coke", "Juice", "Water"],
array2 = ["35", "17", "21", "99"],
result = [], i = -1;
while ( array1[++i] ) {
result.push( [ array1[i], array2[i] ] );
}
As written, this solution assumes you will only ever be using strings. 如上所述,此解决方案假设您将只使用字符串。 As @ajax333221 has pointed out in the comments below, this would cause problems if you were to involve boolean
or int
values into this solution. 正如@ ajax333221在下面的注释中指出的那样,如果您将boolean
或int
值包含在此解决方案中,这将导致问题。 As such, I'd like to propose an improvement that will accomplish your goals, while not tripping over difficult values and types: 因此,我想提出一项改进,以实现您的目标,同时不会绊倒困难的价值观和类型:
var array1 = [false, 0, "Juice", -1],
array2 = ["35", "17", "21", "99"],
result = [];
for ( var i = 0; i < array1.length; i++ ) {
result.push( [ array1[i], array2[i] ] );
}
You can use .map()
on Arrays. 你可以在Arrays上使用.map()
。
var Values = array1.map(function(v,i) {
return [v, array2[i]];
});
See the MDN shim for older browsers. 请参阅旧版浏览器的MDN垫片 。
live demo: http://jsfiddle.net/D9rjf/ 现场演示: http : //jsfiddle.net/D9rjf/
If you're going to do this operation quite a bit, you could make a reusable function. 如果您要进行相当多的操作,可以创建一个可重用的函数。
In this example, I extended Array.prototype
, but that's not necessary if you don't like that. 在这个例子中,我扩展了Array.prototype
,但如果你不喜欢它,那就没有必要了。
Array.prototype.combine = function(arr) {
return this.map(function(v,i) {
return [v, arr[i]];
});
};
var Values = array1.combine(array2);
live demo: http://jsfiddle.net/D9rjf/1/ 现场演示: http : //jsfiddle.net/D9rjf/1/
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.