Home > Blockchain >  Trying to create a gird using a 2D Array and nested loop but get undefined as a result within the ar
Trying to create a gird using a 2D Array and nested loop but get undefined as a result within the ar

Time:08-04

function makeGrid(numColumns, numRows) {
  var grid = [];
  var rows = [];

  var columns = [];
  for(let i = 0; i < numRows; i  ) { 
     grid[i] = [];
     for(let j = 0; j < numColumns; j  ) {
       grid[i][j] = columns[j];
     }
  }
  return grid;
}

console.log(makeGrid(3,4));
.as-console-wrapper {max-height: 100% !important;top: 0;}
.as-console-row::after {display: none !important;}

CodePudding user response:

It might be couse u assaign empty values like grid[i] = [] and grid[i][j] = columns[j]. What is the purpose ?

CodePudding user response:

You were on the right track! Just like you had to create an array for each row, you have to also create an array for each column:

function makeGrid(numColumns, numRows){
  const grid = [];
  for(let i = 0; i < numRows; i  ){
     grid[i] = [];
     for(let j = 0; j < numColumns; j  ){
       grid[i][j] = []; // Previously: columns[j]
     }
  }
  return grid;
}

console.log(makeGrid(3,4));

On closer inspection after this fix, your variables rows and columns were unused. I removed them.

Also, you should prefer let and const over var, where applicable. In short: let and const are more similar to how variable declarations and scoping work in other languages, and unlike var they don't come with the (potentially confusing) features of being hoisted and redeclarable.

  • Related