gpt4 book ai didi

javascript - 嵌套 forEach 意外覆盖

转载 作者:行者123 更新时间:2023-11-30 21:01:38 25 4
gpt4 key购买 nike

<分区>

我正在尝试制作一个函数,将数组的所有“水平值”转换为“垂直值”,以便每个 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] 索引?

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com