新手求助:使用Javascript从JSON习题库随机选取10道习题
从JSON题库中随机选取10道习题的实现方法
嘿,作为JavaScript新手能自己动手构建题库,已经迈出很棒的一步啦!针对你这个需求,我给你分享两种实用的实现思路,代码都很容易理解~
方法一:Fisher-Yates洗牌算法(推荐,高效无重复)
这个算法是业界常用的随机打乱数组的方法,能保证每道题被选中的概率均等,而且不会重复选取。步骤很简单:先把整个题库数组打乱,然后取前10个元素就行。
代码示例:
// 假设你的题库数据是这个结构 const questionBank = { "questionlist": [ { "question":"Test question 1", "option1":"Answer1A", "option2":"Answer1B", "option3":"Answer1C" }, { "question":"Test question 2", "option1":"Answer2A", "option2":"Answer2B", "option3":"Answer2C" }, // ... 更多题目 ] }; function getRandomQuestions(bank, count) { // 先复制一份数组,避免修改原数据 const questions = [...bank.questionlist]; let currentIndex = questions.length; let randomIndex; // Fisher-Yates洗牌过程 while (currentIndex !== 0) { randomIndex = Math.floor(Math.random() * currentIndex); currentIndex--; // 交换当前元素和随机选中的元素 [questions[currentIndex], questions[randomIndex]] = [questions[randomIndex], questions[currentIndex]]; } // 取前count个元素,如果题库总数不足count,就返回所有题目 return questions.slice(0, Math.min(count, questions.length)); } // 调用函数获取10道随机题 const random10Questions = getRandomQuestions(questionBank, 10); console.log(random10Questions);
方法二:随机索引选取(适合小题库)
如果你的题库规模不大,也可以用这种方法:不断生成随机索引,把没选过的题目加入结果列表,直到凑够10道或者用完所有题目。
代码示例:
function getRandomQuestionsSimple(bank, count) { const allQuestions = bank.questionlist; const selected = []; const usedIndexes = new Set(); while (selected.length < count && usedIndexes.size < allQuestions.length) { const randomIdx = Math.floor(Math.random() * allQuestions.length); if (!usedIndexes.has(randomIdx)) { usedIndexes.add(randomIdx); selected.push(allQuestions[randomIdx]); } } return selected; } // 调用示例 const random10 = getRandomQuestionsSimple(questionBank, 10); console.log(random10);
注意事项
- 如果你的题库总题数少于10道,上面两个函数都会自动返回所有题目,避免报错。
- 我在代码里都用了数组复制(
[...bank.questionlist]),这样不会修改你原始的题库数据,这点很重要哦~ - 两种方法都能保证选取的题目不重复,Fisher-Yates算法在题库量大的时候效率更高,因为不需要重复判断索引是否已使用。
内容的提问来源于stack exchange,提问作者JSJS
相关产品推荐
相关产品推荐

