简体   繁体   中英

es6 way to create an array of arrays with random numbers?

Trying to create an array of arrays of value 1 or 0. But each array has either [0,0,0,0,0,0] or [1,1,1,1,1,1] since fill isn't a callback. I need it random like [0, 1, 0, 0, 1] What would be an es6 way of creating an array of arrays of values 0 or 1?

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})

I can do this with for loops but I want it more declarative.

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

}

You can use Array#from to create the outer and inner arrays. Since Array#from expects an object with the length property, you can supply height or width as the length, and use the callback to generate whatever values you need in to array.

 const createBoard = ({width, height}) => Array.from({ length: height }, () => Array.from({ length: width }, () => Math.floor(Math.random() * 2) ) ); const board = createBoard({width: 5, height: 10}); console.log(JSON.stringify(board)); 

进行少量更改即可继续执行您的逻辑,这应该可行

x = Array(5).fill([]).map(x => (Math.random(0,1) < 0.5) ? 0 : 1 )

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM