Javascript多维数组键 - val

时间:2017-06-22 05:37:19

标签: javascript arrays multidimensional-array

在我的javascript函数中,我有两个单独的数组:

var row = ["var1","var2","var3"];
var col = ["res1","res2","res3"];

我会创建一个多维数组,如:

  

[[" VAR1"" RES1"],[" VAR2"" RES2"],[" VAR3& #34;" RES3"]]

我试过了:

new Array(m).fill(new Array(n).fill(0));

或解决方案如:

var dict = [[]];
for (i = 0; i < descendents.length; i++) {
    e = descendents[i];
    dict[i] = dict[i][e.id]
    dict[i] = dict[i][e.value]
}

但结果对我不正确。我不知道如何实现这个

提前致谢

1 个答案:

答案 0 :(得分:0)

使用Array#map根据现有数据生成新数组。

&#13;
&#13;
var row = ["var1", "var2", "var3"];
var col = ["res1", "res2", "res3"];
 
// iterate and generate new array based on row array element
// and fetch element from col using the same index
var res = row.map((v, i) => [v, col[i]]);

console.log(res)
&#13;
&#13;
&#13;

或者Array.from带有地图功能。

&#13;
&#13;
var row = ["var1", "var2", "var3"];
var col = ["res1", "res2", "res3"];

var res = Array.from({ length: row.length }, (_, i) => [row[i], col[i]]);

console.log(res)
&#13;
&#13;
&#13;