当前位置:首页 > JavaScript

js实现选题

2026-02-28 19:29:58JavaScript

实现随机选题功能

在JavaScript中实现随机选题功能可以通过以下方式完成。假设有一个题目数组,需要从中随机选取若干题目。

定义题目数组

const questions = [
  "题目1: JavaScript的基本数据类型有哪些?",
  "题目2: 解释闭包的概念",
  "题目3: 什么是事件冒泡?",
  "题目4: 如何实现深拷贝?",
  "题目5: Promise有哪些状态?"
];

简单随机选择单个题目

js实现选题

function getRandomQuestion() {
  const randomIndex = Math.floor(Math.random() * questions.length);
  return questions[randomIndex];
}

实现不重复随机选择多个题目

如果需要选择多个不重复的题目,可以使用以下方法:

方法一:使用Set存储已选索引

js实现选题

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实现图片上传

图片上传的基本实现 使用HTML的<input type="file">元素配合JavaScript的File API可以实现图片上传功能。HTML部分需要创建一个文件选择输入框和一个用于…

js类实现

js类实现

使用类实现 JavaScript 功能 在 JavaScript 中,类(Class)是一种语法糖,基于原型继承机制。通过 class 关键字可以更直观地定义对象模板。 基本类定义 class…

js实现祖玛

js实现祖玛

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

节流js实现

节流js实现

节流(Throttle)的实现原理 节流是一种限制函数执行频率的技术,确保函数在一定时间间隔内最多执行一次。适用于高频触发事件(如滚动、输入、窗口调整等)的场景。 基础实现方式 使用时间戳判断是否执…

js实现图片移动

js实现图片移动

使用CSS和JavaScript实现图片移动 方法一:使用CSS动画结合JavaScript控制 通过CSS定义动画关键帧,JavaScript动态添加或移除动画类。 /* CSS部分 */ .m…

js 实现mvc

js 实现mvc

MVC 模式简介 MVC(Model-View-Controller)是一种软件设计模式,将应用程序分为三个核心组件:模型(Model)处理数据和业务逻辑,视图(View)负责展示数据,控制器(Con…