メモ。目新しいことは書いてない。
普通にやる
普通にやるとこんな感じ。
function randomSelect(array){
let index = Math.floor(Math.random() * array.length)
return array[index]
}
let fruits = ["apple", "orange", "banana"]
console.log(randomSelect(fruits)) // →banana
prototype拡張で書く
個人的にはなんかこの書き方が好きじゃないので、prototype
に直接拡張してみた。
Array.prototype.lot = function(){
let index = Math.floor(Math.random() * this.length)
return this[index]
}
let fruits = ["apple", "orange", "banana"]
console.log(fruits.lot()) // →banana
lotはくじという意味。可読性的にはrandomとかrandomSelectとかのほうがいいと思う。
取り出した要素を配列から削除するバージョン。
Array.prototype.pick = function(){
let index = Math.floor(Math.random() * this.length)
return this.splice(index,1)[0]
}
let fruits = ["apple", "orange", "banana"]
console.log(fruits.pick()) // →banana
console.log(fruits) // →["apple","orange"]
prototype拡張しても大丈夫な時しか使えないけど、メソッドチェーンぽく使えてちょっと便利……かもしれない。好みの問題かな?
今書いてるやつでこういう処理を頻繁にやるので、導入してみたらちょっといい感じになったよというお話でした。