js实现选题
实现随机选题功能
在JavaScript中实现随机选题功能可以通过以下方式完成。假设有一个题目数组,需要从中随机选取若干题目。
定义题目数组
const questions = [
"题目1: JavaScript的基本数据类型有哪些?",
"题目2: 解释闭包的概念",
"题目3: 什么是事件冒泡?",
"题目4: 如何实现深拷贝?",
"题目5: Promise有哪些状态?"
];
简单随机选择单个题目
function getRandomQuestion() {
const randomIndex = Math.floor(Math.random() * questions.length);
return questions[randomIndex];
}
实现不重复随机选择多个题目
如果需要选择多个不重复的题目,可以使用以下方法:
方法一:使用Set存储已选索引
function getRandomQuestions(count) {
if (count > questions.length) {
throw new Error("请求的题目数量超过题库总量");
}
const selectedIndices = new Set();
const result = [];
while (result.length < count) {
const randomIndex = Math.floor(Math.random() * questions.length);
if (!selectedIndices.has(randomIndex)) {
selectedIndices.add(randomIndex);
result.push(questions[randomIndex]);
}
}
return result;
}
方法二:洗牌算法随机排序后截取
function getRandomQuestions(count) {
// 创建副本避免修改原数组
const shuffled = [...questions];
// Fisher-Yates洗牌算法
for (let i = shuffled.length - 1; i > 0; i--) {
const j = Math.floor(Math.random() * (i + 1));
[shuffled[i], shuffled[j]] = [shuffled[j], shuffled[i]];
}
return shuffled.slice(0, count);
}
加权随机选题实现
如果题目有不同的权重(如难度系数),可以使用加权随机算法:
const weightedQuestions = [
{ text: "简单题", weight: 0.6 },
{ text: "中等题", weight: 0.3 },
{ text: "难题", weight: 0.1 }
];
function getWeightedRandomQuestion() {
const totalWeight = weightedQuestions.reduce((sum, q) => sum + q.weight, 0);
let random = Math.random() * totalWeight;
for (const question of weightedQuestions) {
if (random < question.weight) {
return question.text;
}
random -= question.weight;
}
return weightedQuestions[0].text; // 默认返回第一个
}
前端界面实现示例
结合HTML实现简单的随机选题界面:
<div id="question-container"></div>
<button id="random-btn">随机选题</button>
<script>
document.getElementById('random-btn').addEventListener('click', function() {
const randomQuestion = getRandomQuestion();
document.getElementById('question-container').textContent = randomQuestion;
});
</script>
注意事项
- 题库较大时,洗牌算法可能影响性能,应考虑使用Set方法
- 需要处理请求数量超过题库总量的边界情况
- 实际应用中可能需要从服务器获取题目数据
- 加权随机算法需要确保权重总和为1或做归一化处理







