LoginSignup
0
0

More than 3 years have passed since last update.

JSのArrayに「ランダムに要素を返す」メソッドを生やす

Posted at

メモ。目新しいことは書いてない。

普通にやる

普通にやるとこんな感じ。

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拡張しても大丈夫な時しか使えないけど、メソッドチェーンぽく使えてちょっと便利……かもしれない。好みの問題かな?
今書いてるやつでこういう処理を頻繁にやるので、導入してみたらちょっといい感じになったよというお話でした。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0