首页 > 解决方案 > 当我使用 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);

标签: javascriptconsole.lognested-for-loop

解决方案


因为你一直在使用同一个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);


推荐阅读