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

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