▲TOPへ戻る

【javascript】シャッフルする関数を作り、配列の中身をシャッフルさせる方法

疑似要素

以下のように、配列の中身をシャッフルし、表示させる方法について紹介します。

No. 段位 名前 年齢

シャッフルさせる関数

  function shuffle(arrays) {
    const array = arrays.slice();
    for (let i = array.length - 1; i >= 0; i--) {
      const randomIndex = Math.floor(Math.random() * (i + 1));
      [array[i], array[randomIndex]] = [array[randomIndex], array[i]];
    }
    return array;
  }

数字をシャッフルさせる

シャッフルする関数さえあれば、後は配列の変数を引数に渡すだけでシャッフルしてくれます。

  const numbers = [0, 1, 2, 3, 4];
  console.log(shuffle(numbers));

連想配列をシャッフルさせてテーブルで表示

配列の中身をシャッフルしてから、HTMLを生成し表にします。

  function shufflePlayer() {
    const shuffled = shuffle(shogPlayers);  //  配列の中身をシャッフル
    const playerList = document.getElementById("playerList");
    playerList.innerHTML = "";

    shuffled.forEach((player) => {
      const tr = document.createElement("tr");
      playerList.appendChild(tr);
      const keyArray = Object.entries(player);
      keyArray.forEach((key) => {
        const td = document.createElement("td");
        td.textContent = key[1];
        tr.appendChild(td);
      });
    });
  }
  shufflePlayer(); 

参考

js
【javascript】連想配列をテーブルできれいに表示する方法
js
【javascript】オブジェクトの値を取得するObject.keys Object.values Object.entriesの使い方

こんな記事も読まれています。

profile

パソコン好きなガオ

コロナ禍によるステイホームを機にプログラミングを学ぶ。パソコンに関してはプロではないが、ちょっと詳しい程度。

パソコン

javascript

カメラ

ブログ