Nの外部記憶

作ったアプリや、作成時の備忘録を書くブログ。やりたいことが多すぎるッ!

【javascript】カードをシャッフルする

参考コード

'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();
  });
}

解説

参考

JavaScript:配列内の要素をシャッフル(ランダムソート)する方法