繁体   English   中英

插入到已用空 Arrays 填充的二维数组的行中时,元素被添加到每一行

[英]elements are being added to every row when inserting into a row for a 2D array that has been filled with empty Arrays

我正在创建一个新矩阵,我想在其中获取原始矩阵的行并将它们制成列,以及将原始矩阵的列制成行。

一个矩阵:

[[1,2]             
 [3,4]             [[1,3,5]
 [5,6]] turns into  [2,4,6]]

当我在使用 fill() 方法创建行时初始化新矩阵时,插入一行时,每一行的插入都重复。

const arrOne = [[1,2,3],[4,5,6],[7,8,9]]

var transpose = function(matrix) {
    const transposedArr = new Array(matrix[0].length).fill(new Array()); // initializes array to [ [], [], [] ]
        
    //iterate through row
    for(let i = 0; i < matrix.length; i++) {        
        //iterate through columns at row
        for(let j = 0; j < matrix[i].length; j++) {
            transposedArr[j].push(matrix[i][j])
        }
    }
    return transposedArr;
};
console.log(transpose(arrOne));

这将打印

[
  [1, 2, 3, 4, 5, 6, 7, 8, 9],
  [1, 2, 3, 4, 5, 6, 7, 8, 9],
  [1, 2, 3, 4, 5, 6, 7, 8, 9],
]

当我使用 for 循环初始化我的数组时,我没有得到重复的条目

const arrOne = [[1,2,3],[4,5,6],[7,8,9]]

var transpose = function(matrix) {
    const transposedArr = [] // initializing using const transposedArr = Array() also works!
    for(let i = 0; i < matrix[0].length; i++) { // initializes array to [ [], [], [] ]
        transposedArr.push(new Array())
    } 
        
    //iterate through row
    for(let i = 0; i < matrix.length; i++) {        
        //iterate through columns at row
        for(let j = 0; j < matrix[i].length; j++) {
            transposedArr[j].push(matrix[i][j])
        }
    }
    return transposedArr;
};
console.log(transpose(arrOne));

这将打印:

[ 
 [ 1, 4, 7 ],
 [ 2, 5, 8 ],
 [ 3, 6, 9 ] 
]

:为什么当我使用 fill() 方法初始化数组时,它会重复我对每一行的插入?

我在处理这个 Leetcode 问题时遇到了这个问题: https://leetcode.com/problems/transpose-matrix/

我还在 repl 中测试了这段代码。 这是为了确保它在 Leetcode 的环境中不是问题。

 const matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]; /* Allocate newMatrix array */ const newMatrix = []; for (const i in matrix) { const temp = []; for (const j in matrix[i]) temp.push(matrix[j][i]); newMatrix.push(temp); } console.log(newMatrix);

首先,我创建了一个与第一个数组(Rows = Cols / Cols = Rows)长度相反的新数组。

然后你只需要用[i][j] = [j][i]初始化第二个数组,这样它就会将原始矩阵的列初始化为新矩阵的行。

希望你明白。

顺便说一句,填充方法将数组元素“填充”为 STATIC 值,参数应该是(值、开始、结束)。

文档: Array.prototype.fill()

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM