javascript - 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 }
解决方案
推荐阅读
- linux - Linux 将 USB 端口与设备关联
- duplicates - Artemis 在故障转移后收到重复消息
- macos - 使用 launchctl 2,如何从已经在 macOS >= 10.10 上运行的服务推断域?
- python - Python - 求解瞬态矩阵微分方程
- javascript - 为什么我的网页内容重叠?
- c# - Swagger Web 应用程序的 Azure Blob 获取错误之后
- python - 变量的内联初始化
- javascript - 如何在javascript中每5个数字的范围之间生成随机数
- arrays - 数组元素的乘积
- javascript - 仅当 X 大于时才显示 ChartJS 数据