嵌套forEach意外覆盖

时间:2017-11-02 18:12:48

标签: javascript arrays foreach

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

2 个答案:

答案 0 :(得分:1)

因为Array.fill

  

fill() 方法使用静态值将数组的所有元素从起始索引填充到结束索引。

获取静态值并使用它填充数组。因此,您可以在init的每个元素中获得相同的填充数组。



const horizToVert = (arg) => {
    const init = Array(arg.length).fill(Array(arg[0].length).fill(''));

    init[1][2] = 'foo';

    //arg.forEach((value, index) => value.forEach((value2, index2) => {
    //    init[index2][index] = value2;
    //    console.log(init);
    //}));
    return init;
}

let board = [['00', '10', '20'], ['01', '11', '21'], ['02', '12', '22']];

let col = horizToVert(board);

console.log(JSON.stringify(col, 0, 4));

.as-console-wrapper { max-height: 100% !important; top: 0; }




要获得一个独立的填充数组,可以使用Array.from并使用映射值映射一个新数组。



var array = Array.from({ length: 3 }, _ => Array.from({ length: 3 }, _ => 4));

array[0][0] = 0;
console.log(array);

.as-console-wrapper { max-height: 100% !important; top: 0; }




您可以将默认数组用于非exresnd数组,并将值分配给切换索引。



var array = [['00', '10', '20'], ['01', '11', '21'], ['02', '12', '22']],
    result = array.reduce(
        (r, a, i) => (a.forEach((v, j) => (r[j] = r[j] || [])[i] = v), r),
        []
    );

console.log(result);

.as-console-wrapper { max-height: 100% !important; top: 0; }




答案 1 :(得分:0)

你可以这样使用。



let board = 
[ [ '00', '10', '20' ], 
[ '01', '11', '21' ], 
[ '02', '12', '22' ] ];


var transpond = board[0].map((col, i) => board.map(row => row[i]));

console.log(transpond);