I created an array using the array class with size of 8 * 8 and filling it with a dumy object using fill . and after that I created a for and assigning the values . but when I p
In JS objects are passed by reference, so when you do
var gameGrid = new Array(gridSize * gridSize).fill({
loc: null,
color: null,
index: null,
value: null
});
the same object is put in each spot - if you update any of them, you update "all" of them. What you need to do is put a different object in each spot by doing:
var gameGrid = new Array(gridSize * gridSize).fill(null).map(i => ({
loc: null,
color: null,
index: null,
value: null
});
var gridSize = 8;
const colorname = ["Red", "Orange", "Green", "Blue", "Purple", "Yellow"];
var gameGrid = new Array(gridSize * gridSize).fill(null).map(i => ({
loc: null,
color: null,
index: null,
value: null
}));
fillTheGrid();
function fillTheGrid() {
for (var i = 0; i < gridSize * gridSize; i++) {
addElement(i)
}
}
// actual code Is big so im using I for index and value
function addElement(i){
gameGrid[i].loc = i;
let randomColor = Math.floor(Math.random() * colorname.length);
gameGrid[i].color = colorname[randomColor];
gameGrid[i].index = i;
gameGrid[i].value = i;
}
console.log(gameGrid);