当前位置:首页 > JavaScript

js实现选题

2026-02-28 19:29:58JavaScript

实现随机选题功能

在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或做归一化处理

js实现选题

标签: js
分享给朋友:

相关文章

js实现跳转

js实现跳转

使用 window.location 跳转 通过修改 window.location.href 实现页面跳转,这是最常用的方法。 window.location.href = 'https:/…

js实现验证码

js实现验证码

使用Canvas生成图形验证码 在HTML中创建一个Canvas元素用于绘制验证码。通过JavaScript随机生成数字或字母组合,并添加干扰线、噪点等干扰元素增强安全性。 <canvas i…

js实现图片轮播

js实现图片轮播

实现基础图片轮播 使用HTML、CSS和JavaScript创建一个简单的图片轮播。HTML部分定义轮播容器和图片,CSS设置样式和动画效果,JavaScript处理轮播逻辑。 <div c…

js实现拷贝

js实现拷贝

实现文本拷贝 使用 document.execCommand 方法(已废弃但兼容性较好): function copyText(text) { const textarea = documen…

js实现祖玛

js实现祖玛

实现祖玛游戏的核心思路 祖玛游戏的核心玩法是发射彩色珠子,形成三个或以上相同颜色的珠子即可消除。以下是使用JavaScript实现的基本框架。 游戏初始化 创建画布并初始化游戏状态: cons…

js实现图

js实现图

JavaScript 实现图的常用方法 在 JavaScript 中,图(Graph)可以通过多种方式实现,常见的包括邻接表(Adjacency List)和邻接矩阵(Adjacency Matrix…