Home > Enterprise >  how to trace the for loop
how to trace the for loop

Time:09-01

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(JSON.stringify(matrix));

this code should print this

[[0,0], [0,0,0,0], [0,0,0,0,0,0]]

but instead its printing this

[[0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0]]

can someone trace the code?

CodePudding user response:

I think this is about variable scope.you should declare row in for loop

CodePudding user response:

When you push row, you are not pushing the contents of the row array, you are pushing a reference to the row array. As the row array changes through the loops, the values in the reference are updating.

If you slice() the row array when you push it into the new array, you will copy the values of the array, instead of a reference to it:

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.slice());
  }
  return newArray;
}

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

output:

[[0, 0], [0, 0, 0, 0], [0, 0, 0, 0, 0, 0]]

See:

Copy array by value

CodePudding user response:

a solution...

function zeroArray(m, n)
  {
  let newArray = new Array(m)
    , count    = n
    ;      
  for (let i = 0; i < m; i  , count  = n)
    newArray[i] = new Array(count).fill(0)
    ;
  return newArray
  }

let matrix = zeroArray(3, 2);

console.log(JSON.stringify(matrix));

  • Related