如何使用JavaScript随机化有序列表

How do i randomize an Ordered List using JavaScript

本文关键字:列表 随机化 何使用 JavaScript      更新时间:2023-12-15

我正在做一个包含问题的测试。

我希望问题随机出现在页面上,而不是按顺序列出。

这是我的HTML:

<ol id = "questionList">
<li id="question">Question text<br/></li>
<li id="question">Question text<br/></li>
</ol>

这是我的javascript:

var questionsList = document.getElementById('question');
var questionArray=[];
var randomize;
for (var i=0; questionsList.length>0; i++) {
        questionArray[i]=questionList[i];
}
randomize = questionArray.Math.random()*questionList.length;
document.getElementById("questionsList").innerHTML= randomize;

我不知道如何让问题随机出现,而不是从#1到#10。

感谢您的帮助。

已经提出了一个问题(如何随机化(搅乱)JavaScript数组?)

但这是最基本的:

一个坚实的洗牌算法是Fisher Yates(又名Knuth)洗牌。

请参阅https://github.com/coolaj86/knuth-shuffle

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;
}

你可以这样使用它:

var arr = ["question 1", "question 2"];
shuffle(arr);
console.log(arr);