首页 > 解决方案 > js在循环内设置随机值

问题描述

我尝试在反应类中的 js 循环中设置一个随机值 - 当我在循环内 console.log 时,我得到了不同的随机值,但在循环外,我的函数返回数组中所有元素的最后生成的随机值 - 为什么?

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)

第一个控制台日志结果 - 工作正常

0.7381104974410921  
0.803021327539017  
0.689253948016345  
0.2597936599628139

第二个给我所有元素相同的结果

Object { open: true, bomb: 0.2597936599628139 }  
Object { open: true, bomb: 0.2597936599628139 }  
Object { open: true, bomb: 0.2597936599628139 }  
Object { open: true, bomb: 0.2597936599628139 }

标签: javascriptreactjsloops

解决方案


推荐阅读