Tbpgr Blog

Employee Experience Engineer tbpgr(てぃーびー) のブログ

JavaScriptで配列の1要素をランダムで抽出するクラス(RandomListSelector)

JavaScriptで配列の1要素をランダムで抽出するクラスを作成。

作りはシンプルで

  • コンストラクタに配列を設定
  • 配列の要素範囲で乱数を生成
  • ランダムに配列の添字を指定して返却。

以下がサンプルコード。

var RandomListSelector = function(list) {
	this.list = list;
};

RandomListSelector.prototype.getRandomElement = function() {
	if (this.list==null || this.list.length == 0) {
		alert("リストが初期化されていないか、要素が空です");
		return;
	}
	var randomizeIndex = Math.floor(Math.random() * this.list.length);
	return this.list[randomizeIndex];
};

※利用側
var arrayList = new Array();
var randomListSelector = new RandomListSelector(arrayList);
var randomResult = randomListSelector.getRandomElement();