React - 使用 .map 和 .fill 用随机数填充二维数组
React - Filling 2D array with random numbers using .map and .fill
我在 state/the 构造函数中定义的 React 项目中有一个二维数组,如下所示:
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 之间的随机数填充二维数组。如果我使用 .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)
成功将随机数放入二维数组的一维。我如何嵌套第二个 .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() ) );
我在 state/the 构造函数中定义的 React 项目中有一个二维数组,如下所示:
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 之间的随机数填充二维数组。如果我使用 .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)
成功将随机数放入二维数组的一维。我如何嵌套第二个 .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() ) );