In a constructor, I'm creating a two dimensional array like so:
this.grid = Array.apply(null, Array(3)).map((el, i) => {
return Array.apply(null, Array(3)).map((el, i) => {
return {
key1: null,
key2: null
};
});
});
After i console.log(this.grid) I get a two-dimensional array with the objects and null properties. however if I try to console.log(JSON.stringify(this.grid[0][1])) there's an undefined error on [1]
class Grid {
constructor() {
this.grid = Array.apply(null, Array(3)).map((el, i) => {
return Array.apply(null, Array(3)).map((el, i) => {
return {
key1: null,
key2: null
};
});
});
}
}
// used in another external class with require() and instantiated like:
let grid = new Grid();
console.log(grid);
console.log(JSON.stringify(grid[0][1]))
I understand some differences between constructing arrays with the constructor, and using Array.apply(). Maybe I'm using apply() incorrectly?
I've attempted constructing this array in multiple ways. from a nested for-loop where .push()ing the same objects to the second dimension and then each row the grid.
this.grid = []
for(let i = 0; i < 3; ++i){
let row = []
for( let j =0; j< 3; ++j) {
let obj = {
key1: "property",
key2: "property"
}
row.push(obj);
}
this.grid.push(row);
}
class Grid {
constructor() {
this.grid = [];
for (let i = 0; i < 3; ++i) {
let row = [];
for (let j = 0; j < 3; ++j) {
let obj = {
key1: null,
key2: null
};
row.push(obj);
}
this.grid.push(row);
}
}
}
// used in another external class file with a require() and instantiation like so:
let grid = new Grid();
console.log(JSON.stringify(grid[0][1]));
I expect the log to show the object at those respective indices. However, JSON.stringify(this.grid[0][1]) is still:
TypeError: Cannot read property '1' of undefined