首页 > 解决方案 > 努力理解这个多层 for 循环是如何工作的

问题描述

问题

以下函数应该创建一个具有 m 行和 n 列零的二维数组。

回答

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);

我的问题

我熟悉在 for 循环内有一个 for 循环,以遍历数组的第二层。但在这个例子中,它似乎特别令人困惑。

请你一步一步解释这里发生了什么。

标签: javascriptloops

解决方案


实际上,此代码不起作用。如果你运行它,你会看到它创建了一个 3x6 而不是 6x3 的数组。

试试这个

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

    // 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);

您需要在推送后重新初始化该行,或者,甚至更好

function zeroArray(m, n) {
  // Creates a 2-D array with m rows and n columns of zeroes
  let newArray = [];
    let row = [];
    // 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);
    }
  for (let i = 0; i < m; i++) {
    // 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);

不要重新做初始化行的工作,因为所有的行都是一样的


推荐阅读