Javascript es6创建随机数数组的方法?
正在尝试创建值为1或0的数组数组。但是每个数组都有[0,0,0,0,0,0]或[1,1,1,1,1,1],因为fill不是回调。我需要它像[0,1,0,0,1]一样随机。创建一个值为0或1的数组的es6方法是什么Javascript es6创建随机数数组的方法?,javascript,ecmascript-6,Javascript,Ecmascript 6,正在尝试创建值为1或0的数组数组。但是每个数组都有[0,0,0,0,0,0]或[1,1,1,1,1,1],因为fill不是回调。我需要它像[0,1,0,0,1]一样随机。创建一个值为0或1的数组的es6方法是什么 const createBoard = function({width, height}) { const board = Array(height).fill([]) .map(row => row.concat( Array(width).fill( Math.r
const createBoard = function({width, height}) {
const board = Array(height).fill([])
.map(row => row.concat( Array(width).fill( Math.round(Math.random()) ) ))
return board
}
createboard({width: 5, height: 10})
我可以用for循环来实现这一点,但我希望它更具声明性
const createBoard = function({width, height}) {
let board = []
for(let row = 0; row < height; row++) {
board.push([])
for(let cell = 0; cell < width; cell++) {
board[row].push(Math.round(Math.random()))
}
}
return board
const createBoard=函数({width,height}){
让board=[]
for(让行=0;行<高度;行++){
board.push([])
对于(让单元格=0;单元格<宽度;单元格++){
板[row].push(Math.round(Math.random()))
}
}
返回板
}您可以使用创建外部和内部阵列。由于Array#from需要一个具有length
属性的对象,因此可以提供height
或width
作为长度,并使用回调生成数组中所需的任何值
constcreateboard=({width,height})=>
数组。从({length:height},
()=>Array.from({length:width}),
()=>Math.floor(Math.random()*2)
)
);
constboard=createBoard({宽度:5,高度:10});
log(JSON.stringify(board))代码>您可以使用创建外部和内部数组。由于Array#from需要一个具有length
属性的对象,因此可以提供height
或width
作为长度,并使用回调生成数组中所需的任何值
constcreateboard=({width,height})=>
数组。从({length:height},
()=>Array.from({length:width}),
()=>Math.floor(Math.random()*2)
)
);
constboard=createBoard({宽度:5,高度:10});
log(JSON.stringify(board))代码>继续您的逻辑,只需稍作更改,这应该会起作用
x = Array(5).fill([]).map(x => (Math.random(0,1) < 0.5) ? 0 : 1 )
x=Array(5).fill([]).map(x=>(Math.random(0,1)<0.5)?0:1)
继续您的逻辑,只做一些小的更改,这应该会起作用
x = Array(5).fill([]).map(x => (Math.random(0,1) < 0.5) ? 0 : 1 )
x=Array(5).fill([]).map(x=>(Math.random(0,1)<0.5)?0:1)
这似乎不如嵌套for循环可读。我应该只使用for循环吗?但这可能是因为我不习惯这样做,所以我就用这个答案。这似乎比嵌套for循环可读性差。我应该只使用for循环吗?但这可能是因为我不习惯,所以我就用这个答案。