▲TOPへ戻る

【javascript】配列からひとつづつ表示し、表示されたものは配列から削除していく方法

クイズアプリを作る時に必要な部分を紹介します。

問題を配列で準備し、ランダムに1問ずつ表示し、終わった問題は、配列から削除していきます。

  <div class="qWrapper">
    <div id="questions"></div>
    <button type="button" class="nextBtn">Start</button>
  </div>
  .qWrapper{
      width: 80%;
      height: 200px;
      background: rgb(0, 119, 255);
      border-radius: 20px;
      display: flex;
      flex-direction: column;
      justify-content: center;
      align-items: center;
      margin: 0 auto;
      color: #fff;
  }
  #questions{
      font-size: 2em;
      margin: 30px ;
  }
  .nextBtn{
      width: 80px;
      height: 30px;
      font-size: 22px;
      margin: 30px;
  }

Math.floor(Math.random()で、ランダムさせる。

indexOf()で、配列の中から表示された問題を検索

splice()で、検索された問題を配列から削除する。

  let list= ['問題1','問題2','問題3',
                '問題4','問題5','問題6',
                '問題7','問題8','問題9','問題10',]
  const questions = document.getElementById("questions");
  const array = document.getElementById("array");
  const nextBtn = document.querySelector(".nextBtn"); 
  questions.textContent = "スタート!"; 
  array.textContent = list;
  
  nextBtn.addEventListener("click", function () {
    if(list.length===0 && nextBtn.textContent == 'Reset'){
        window.location.reload();
    }else if(list.length===0){
        questions.textContent = '終了!';
        nextBtn.textContent = 'Reset';
        array.textContent = '';     
    }else {
        nextBtn.textContent = 'Next'     
        const questionIndex = list[Math.floor(Math.random() * list.length)];
        questions.textContent = questionIndex;
        array.textContent = list;
        const index1 = list.indexOf(questionIndex);
        list.splice(index1, 1);
    }
  }) 

参考

js
【javascript】 配列を削除、追加するarray.splice()メソッドについて

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

profile

パソコン好きなガオ

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

パソコン

javascript

カメラ

ブログ