【发布时间】:2018-04-15 08:58:30
【问题描述】:
我正在尝试制作一个将数组的所有“水平值”转换为“垂直值”的函数,以便每个 array[i][j] 变成 newarray[j][i]
[ [ '00', '10', '20' ],
[ '01', '11', '21' ],
[ '02', '12', '22' ] ];
应该变成
[ [ '00', '01', '02' ],
[ '10', '11', '12' ],
[ '20', '21', '22' ] ]
这是我目前拥有的脚本:
let board =
[ [ '00', '10', '20' ],
[ '01', '11', '21' ],
[ '02', '12', '22' ] ];
let col;
const horizToVert= (arg)=>{
const init = Array(arg.length).fill(Array(arg[0].length).fill(''));
arg.forEach((value, index) => value.forEach((value2, index2) => {
init[index2][index]=value2; console.log(init);
}));
return init;
}
col = horizToVert(board);
但是由于某种原因,输出对我来说毫无意义:
[ [ '00', '', '' ], [ '00', '', '' ], [ '00', '', '' ] ]
[ [ '10', '', '' ], [ '10', '', '' ], [ '10', '', '' ] ]
[ [ '20', '', '' ], [ '20', '', '' ], [ '20', '', '' ] ]
[ [ '20', '01', '' ], [ '20', '01', '' ], [ '20', '01', '' ] ]
[ [ '20', '11', '' ], [ '20', '11', '' ], [ '20', '11', '' ] ]
[ [ '20', '21', '' ], [ '20', '21', '' ], [ '20', '21', '' ] ]
[ [ '20', '21', '02' ],[ '20', '21', '02' ],[ '20', '21', '02' ] ]
[ [ '20', '21', '12' ],[ '20', '21', '12' ],[ '20', '21', '12' ] ]
[ [ '20', '21', '22' ],[ '20', '21', '22' ],[ '20', '21', '22' ] ]
[Finished in 0.727s]
为什么将例如'00' 分配给所有col[i][0] 索引?
【问题讨论】:
-
啊,很好的矩阵转置。无论如何,看到这个问题:stackoverflow.com/questions/17428587/…
标签: javascript arrays foreach