为什么在我 console.log 矩阵时有 [0][0][0][0][0][0] 中的三个?

问题描述

好的,所以我只想简单解释一下为什么我的控制台中有三个 [0][0][0][0][0][0] 在一个更大的数组中而不是一个?我的问题可能与嵌套 for 循环有关,所以如果你们能准确解释这里发生的事情,我将不胜感激。

function zeroArray(m,n) {
  // Creates a 2-D array with m rows and n columns of zeroes
  let newArray = [];
  let row = [];
  for (let i = 0; i < m; i++) {
    // Adds the m-th row into newArray

    for (let j = 0; j < n; j++) {
      // Pushes n zeroes into the current row to create the columns
      row.push(0);
    }
    // Pushes the current row,which Now has n zeroes in it,to the array
    newArray.push(row);
  }
  return newArray;
}

let matrix = zeroArray(3,2);
console.log(matrix);

解决方法

因为您一直使用相同的 row 数组。只需在每个循环中创建一个新的 row 数组。

function zeroArray(m,n) {
  let newArray = [];
  for (let i = 0; i < m; i++) {
    let row = []; // Create the row inside the loop,so on each iteration a new row is created
    for (let j = 0; j < n; j++) {
      row.push(0);
    }
    newArray.push(row);
  }
  return newArray;
}

let matrix = zeroArray(3,2);
console.log(matrix);

,

这是使用 Array.from() 及其内部映射回调和 new Array 构造函数以及 Array#fill() 的一个很好的用例

function zeroArray(m,n) {
  // Creates a 2-D array with m rows and n columns of zeroes
  return Array.from({length: m},() => new Array(n).fill(0))
}

let matrix = zeroArray(3,2);
console.log(matrix);