【问题标题】:Alternating between players using JavaScript使用 JavaScript 在玩家之间切换
【发布时间】:2021-04-01 20:02:16
【问题描述】:

我正在尝试在玩家之间交替并给每个人一个问题,现在玩家名称存储在一个数组中,我正在尝试随机,但它不起作用。

var counter = 0;
const limit = 4 * localStorage.getItem('playersNum');

nextBtn.addEventListener('click', function() {
  if(counter < limit) {
    // Display player's name and ask question
    for (let i = 0; i < names.length; i++) {
        randomName = names[Math.floor(Math.random()*names.length)];
        const playerName = document.getElementById('card-title');
        playerName.innerText = randomName;

    }
    const h6 = document.getElementById('h6');
    h6.innerHTML = "Question " + (counter + 1);
    nextBtn.innerHTML = "Next";
    // Randomely pick a question from the array
    randomItem = questions[Math.floor(Math.random()*questions.length)];
    random = document.getElementById('questions');
    random.innerText = randomItem;
    counter++; 
  } else {
    alert('No more questions !')
  }
});

【问题讨论】:

    标签: javascript html css dom


    【解决方案1】:

    您可以使用随机播放: [https://*.com/questions/2450954/how-to-randomize-shuffle-a-javascript-array]

    var counter = 0;
    const limit = 4 * localStorage.getItem('playersNum');
    
    questions = shuffle(questions);
    names = shuffle(names);
    nextBtn.addEventListener('click', function() {
        if(counter < limit) {
            // Display player's name and ask question
            randomName = names[counter%names.length];
            const playerName = document.getElementById('card-title');
            playerName.innerText = randomName;
            const h6 = document.getElementById('h6');
            h6.innerHTML = "Question " + (counter + 1);
            nextBtn.innerHTML = "Next";
            // Randomely pick a question from the array
            randomItem = questions[counter)];
            random = document.getElementById('questions');
            random.innerText = randomItem;
            counter++; 
        } else {
            alert('No more questions !')
        }
    });
    
    function shuffle(array) {
      var currentIndex = array.length, temporaryValue, randomIndex;
    
      // While there remain elements to shuffle...
      while (0 !== currentIndex) {
    
        // Pick a remaining element...
        randomIndex = Math.floor(Math.random() * currentIndex);
        currentIndex -= 1;
    
        // And swap it with the current element.
        temporaryValue = array[currentIndex];
        array[currentIndex] = array[randomIndex];
        array[randomIndex] = temporaryValue;
      }
    
      return array;
    }
    

    【讨论】: