React - 使用 .map 和 .fill 用随机数填充 2D 数组



我在 React 项目中有一个 2D 数组,在状态/构造函数中定义,如下所示:

constructor(props){
super(props);
this.state = {
boardHeight: 50,
boardWidth: 30,
iterations: 10,
reset: false,
alive: false,
board: [],
randomNum: ''
};
this.state.board = new Array(this.state.boardHeight).fill(new Array(this.state.boardWidth).fill(0));
}

稍后在我的程序中,我想用一个介于 0 和 1 之间的随机数填充 2D 数组。如果我使用 .map 函数,我可以像这样将一个随机数放入数组中:

componentDidMount = () => {
const data = this.state.board;
// Generates Array of random numbers
const startingBoard = data.map(Math.random)
console.log('Starting board contains ' + startingBoard);
// After startingBoard is working I can set state with startingBoard
this.setState({
board: startingBoard
});
}

const startingBoard = data.map(Math.random)成功地将随机数放入 2D 数组的一个维度中。如何嵌套第二个 .map 函数,以便我可以为此数组的两个维度创建随机数?

我正在将此数组用于游戏板网格。我需要为网格中的任何正方形生成随机数(即 [0][0]、[0][1] 等(,所以我需要能够为这个 2D 数组中的两个数组创建随机数。

像这样:

const starting - data.map((x, index) => {
x.map((y, index) => {
return Math.random;
})
}) 

>.fill(new Array(this.state.boardWidth).fill(0))使用相同的数组实例填充所有行,因此一行中的更改将更改所有行。map可以在fill后用于制作单独的数组:

board = Array(this.state.boardHeight).fill().map(_ => 
Array(this.state.boardWidth).fill().map(_ => Math.random() ) );  

最新更新