Пытаюсь понять, как работает этот многослойный для l oop - PullRequest
0 голосов
/ 06 мая 2020

Вопрос

Следующая функция должна создать двумерный массив с 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);

Мой вопрос

Я знаю, что для l oop внутри a для l oop, чтобы перебирать второй слой массива. Но в этом примере это кажется особенно запутанным.

Не могли бы вы пошагово объяснить, что здесь происходит.

1 Ответ

2 голосов
/ 06 мая 2020

Этот код на самом деле не работает. Если вы запустите его, вы увидите, что он создает массив 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);

Не выполняйте повторную инициализацию строки, поскольку все строки одинаковы

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...