参考コード
'use strict';
{
class CardGame {
constructor() {
this.deck = ["a", "b", "c", "d", "e"];
}
show() {
document.getElementById('deck_value').textContent = "[" + this.deck + "]";
}
shuffle() {
for (let i = this.deck.length - 1; i >= 0; i--){
const j = Math.floor(Math.random() * (i + 1));
[this.deck[i], this.deck[j]] = [this.deck[j], this.deck[i]];
}
}
}
const game = new CardGame();
document.querySelector('button').addEventListener('click', () => {
game.shuffle();
game.show();
});
}
解説
- 「Fisher–Yates shuffle」というアルゴリズムを利用している
参考
JavaScript:配列内の要素をシャッフル(ランダムソート)する方法