本文介绍了将2个数组组合成一个多维数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是基于我的上一个问题。

This is based on my last question.

我有这些数组:

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"]
]

我试过这个剧本:

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

如上所述,此解决方案假设您将只使用字符串。正如@ ajax333221在下面的评论中指出的那样,如果涉及 boolean int 值,这会导致问题进入这个解决方案因此,我想提出一项改进,以实现您的目标,同时不会绊倒困难的价值观和类型:

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. 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] ] );
}

这篇关于将2个数组组合成一个多维数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-14 00:40