2017-06-22 41 views
0

在我的javascript函數我有兩個單一陣列是這樣的:的JavaScript多維數組的鍵 - VAL

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

我會創建一個多維數組,如:

[ 「VAR1」,「RES1 「],[」 VAR2" , 「RES2」],[ 「VAR3」, 「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] 
} 

但結果卻是不適合我是正確的。我不知道如何提前

+0

'row.map((E,I)=>並[e,COL [I]])'' – Tushar

+1

E,COL [I]' - 聽起來像一個病毒:對 –

回答

0

使用Array#map實現這一

由於基於現有的新數組。

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)

或用Array.from與地圖功能。

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)