どうも、ちょげ(@chogetarou)です。
配列(Array)の要素をランダムに取り出す方法を紹介します。
方法

配列(Array)の要素をランダムに取得するには、Math.random()を使います。
まず、配列名の後に[]を記述します。
[]内でMath.floor()を呼び出します。
そして、Math.floor()の引数で、Math.random()と配列のlengthプロパティを掛け算します。
array[Math.floor(Math.random() * array.length)];
上記の配列名[]
は、配列の要素をランダムに取得します。
使用例
function getRandom(array) {
return array[Math.floor(Math.random() * array.length)];
}
var numbers = [1, 2, 3, 4, 5];
for (var i = 0; i < 5; i++) {
console.log(getRandom(numbers));
}
出力:
3
4
5
1
2
コメント