bunty's blog

ググったこととか勉強したことのメモ

JS で配列からランダムな値を取得する

適当な配列の中からランダムで値を取得したかったため、0 ~ 2 の間でランダムな数値を取得したかった。 Math.rondom() に min と max を引数で渡せるのかと思ったけど、引数では渡せないとのこと。

const list = ['a', 'b', 'c']

// これに引数渡せるかと思った
Math.rondom()

ドキュメントに書いてあったのだけども、こんな感じで自前で用意しないといけないらしい。

function getRandomInt(min, max) {
  min = Math.ceil(min);
  max = Math.floor(max);
  return Math.floor(Math.random() * (max - min) + min); //The maximum is exclusive and the minimum is inclusive
}

developer.mozilla.org

上記のコードを用意しておいて使いまわせるようにしておくか、ちょっと書くだけならこんな感じで良さそう。

const list = ['a', 'b', 'c']
const index = Math.floor(Math.random() * list.length)
list[index] // random