ブログ

読んで思い出す。忘れるために書く

いくつかのランダムな数を書き出す

teratail.com

質問を見掛けて、コードを書いたので、こちらにメモ

// Accepts size of generates and number of upto with Object
function randomNumbers (params) {
  return (
    Array.apply(null, Array(params.size))
      .map(() => { return Math.floor(Math.random() * params.upto) })
  )
}

function writeToDocument (array) {
  array.map(function (elm, index) {
    let str = ''.concat('<p>', 'rand', index + 1, ': ',  elm, '</p>')
    document.write(str);
  })
}

function maxNumber (array) {
  return (
    array.slice(0)
      .sort((a, b) => { return a < b })[0]
  )
}

let array = randomNumbers({ size: 3, upto: 101 })
console.log(array) // => [ 78, 57, 18 ]

// writeToDocument(array)
// =>
// <p>rand1: 78</p>
// <p>rand2: 57</p>
// <p>rand3: 18</p>

console.log(maxNumber(array)) // => 78
console.log(array) // => [ 78, 57, 18 ]