0

I try to set a random value in a loop in js inside react class - when I console.log it inside the loop i got different random values but outside the loop my function returns the last generated random value for all elements in the array - why ?

genBomb(chance){
  return (Math.random())
}

genBoard(width, height, chance) {
  let board = new Array(width).fill(new Array(height).fill({}))
  for(let i = 0; i < width; i++){
    for(let j = 0; j < height; j++){
      board[i][j].open = true
      board[i][j].bomb = this.genBomb(chance) 
      console.log(board[i][j].bomb)                //<- first console log
    }
  }
  console.log(board)                              //<- second console.log
  return board
}

this.genBoard(4,4,50)

First console log result - works ok

0.7381104974410921  
0.803021327539017  
0.689253948016345  
0.2597936599628139

Second gives me the same results for all elements

Object { open: true, bomb: 0.2597936599628139 }  
Object { open: true, bomb: 0.2597936599628139 }  
Object { open: true, bomb: 0.2597936599628139 }  
Object { open: true, bomb: 0.2597936599628139 }
Daniel Kukula
  • 333
  • 3
  • 7
  • Don't use `.fill` for non-primitives - use `Array.from` instead – CertainPerformance Jan 06 '19 at 23:23
  • Classic missuse of `.fill`. If you use fill, you'll fill the array with **the same object everytime**. Do this instead: `(new Array(width)).fill().map(() => (new Array(width)).fill().map(() => ({})))` – Nino Filiu Jan 06 '19 at 23:37

0 Answers0