前端实现试卷题目、选项打乱。

选项打乱

// 定义原始选项数组
var options = ["选项1", "选项2", "选项3", "选项4"];
 
// 将选项数组复制到新数组中
var newOptions = [...options];
 
// 打乱选项数组
for (let i = newOptions.length - 1; i > 0; --i) {
    const j = Math.floor(Math.random() * (i + 1)); // 生成[0, i]之间随机索引
    [newOptions[i], newOptions[j]] = [newOptions[j], newOptions[i]]; // 交换位置
}
 
console.log("打乱后的选项列表:",newOptions);

题目打乱

const quesList=[
    {
        "id": 58,
        "dataCate": "question",
        "questionContent": "题干",   
    },
    {
        "id": 59,
        "dataCate": "question",
        "questionContent": "题干22",   
    },
    {
        "id": 60,
        "dataCate": "question",
        "questionContent": "题干33",   
    },
]
for (let i = 0, len = quesList.length; i < len; i++) {
    let currentRandom = parseInt(Math.random() * (len - 1));
    let currentArr = quesList[i];
     quesList[i] = quesList[currentRandom];
      quesList[currentRandom] = currentArr;
}

你可能感兴趣的:(JavaScript,前端,javascript)