如何在JavaScript中从10道试题列表随机抽取5道展示?
实现随机抽取5道试题的两种可行方案
假设你的试题数组结构类似这样:
const allQuestions = [ { id: 1, question: "问题1", options: ["A", "B", "C"], answer: "A" }, { id: 2, question: "问题2", options: ["A", "B", "C"], answer: "B" }, // ... 剩下8道题 ];
这里提供两种用Math.floor(Math.random())实现的方案,你可以根据需求选择:
方案一:Fisher-Yates洗牌后取前5题
这种方法会先打乱整个试题数组,再截取前5个元素,随机性均匀且实现简单:
function getRandomQuestions(questions, count) { // 复制原数组,避免修改原始数据 const shuffled = [...questions]; let currentIndex = shuffled.length; let randomIndex; // Fisher-Yates洗牌核心逻辑 while (currentIndex > 0) { // 生成0到currentIndex-1之间的随机整数 randomIndex = Math.floor(Math.random() * currentIndex); currentIndex--; // 交换当前元素和随机选中的元素 [shuffled[currentIndex], shuffled[randomIndex]] = [shuffled[randomIndex], shuffled[currentIndex]]; } // 返回前count个随机试题 return shuffled.slice(0, count); } // 调用函数抽取5道题,传入你的渲染逻辑 const selectedQuestions = getRandomQuestions(allQuestions, 5); renderQuiz(selectedQuestions);
方案二:随机选取不重复索引(不打乱原数组)
如果不想改动原数组结构,可以通过随机生成索引的方式挑选5道不重复的试题:
function getRandomQuestions(questions, count) { const selectedIndices = new Set(); const selected = []; // 循环直到选够指定数量的试题 while (selectedIndices.size < count) { // 生成0到试题总数-1之间的随机索引 const randomIndex = Math.floor(Math.random() * questions.length); // 确保索引未被选中过,避免重复试题 if (!selectedIndices.has(randomIndex)) { selectedIndices.add(randomIndex); selected.push(questions[randomIndex]); } } return selected; } // 调用方式同上 const selectedQuestions = getRandomQuestions(allQuestions, 5); renderQuiz(selectedQuestions);
关键逻辑说明
两种方案都用到了Math.floor(Math.random() * max),核心作用是生成0到max-1之间的合法数组索引:
Math.random()返回0(包含)到1(不包含)的随机小数- 乘以数组长度后,得到0到数组长度(不包含)的数值
Math.floor()向下取整,最终得到符合数组下标规则的整数
你只需要将上述函数整合到现有代码中,替换原来直接使用全部试题的逻辑即可。
内容的提问来源于stack exchange,提问作者Dzontra
相关产品推荐
相关产品推荐

