js实现随机题库
实现随机题库的基本思路
使用JavaScript实现随机题库的核心在于数据结构的设计和随机算法的应用。题库通常以数组或对象形式存储,随机抽取题目可通过数组的随机索引或洗牌算法实现。
数据结构设计
建议将题库设计为对象数组,每个对象包含题目、选项和答案等属性:

const questionBank = [
{
question: "问题1",
options: ["选项A", "选项B", "选项C"],
answer: 0 // 正确答案的索引
},
{
question: "问题2",
options: ["选项A", "选项B", "选项C"],
answer: 1
}
// 更多题目...
];
随机抽取单题
通过生成随机索引从题库中抽取题目:
function getRandomQuestion() {
const randomIndex = Math.floor(Math.random() * questionBank.length);
return questionBank[randomIndex];
}
随机排序整个题库
使用Fisher-Yates洗牌算法实现题库的随机排序:

function shuffleArray(array) {
for (let i = array.length - 1; i > 0; i--) {
const j = Math.floor(Math.random() * (i + 1));
[array[i], array[j]] = [array[j], array[i]];
}
return array;
}
const shuffledQuestions = shuffleArray([...questionBank]);
避免重复抽题
当需要保证不重复抽取时,可结合数组操作实现:
function getUniqueQuestions(count) {
const shuffled = shuffleArray([...questionBank]);
return shuffled.slice(0, count);
}
题目难度分级
对题目进行难度分级后随机抽取:
const questionBank = {
easy: [...], // 简单题
medium: [...], // 中等题
hard: [...] // 难题
};
function getQuestionByDifficulty(difficulty) {
const pool = questionBank[difficulty];
return pool[Math.floor(Math.random() * pool.length)];
}
完整示例代码
const questionBank = [
{ question: "1+1=?", options: ["1", "2", "3"], answer: 1 },
{ question: "2+2=?", options: ["2", "4", "6"], answer: 1 },
{ question: "3+3=?", options: ["3", "6", "9"], answer: 1 }
];
function getRandomQuiz(num) {
const shuffled = [...questionBank].sort(() => 0.5 - Math.random());
return shuffled.slice(0, num);
}
// 获取2道随机题目
const quiz = getRandomQuiz(2);
console.log(quiz);






