当前位置:首页 > JavaScript

js实现选题

2026-01-14 14:10:58JavaScript

实现选题功能的JavaScript方法

基础实现方案

使用数组存储选项,通过随机索引选取:

const options = ['选项A', '选项B', '选项C', '选项D'];
const randomIndex = Math.floor(Math.random() * options.length);
const selected = options[randomIndex];
console.log(selected);

权重选择实现

为选项添加权重比例:

js实现选题

const weightedOptions = [
  { item: '选项A', weight: 0.1 },
  { item: '选项B', weight: 0.3 },
  { item: '选项C', weight: 0.6 }
];

function weightedRandom(items) {
  const totalWeight = items.reduce((acc, cur) => acc + cur.weight, 0);
  const random = Math.random() * totalWeight;
  let weightSum = 0;

  for (const item of items) {
    weightSum += item.weight;
    if (random <= weightSum) return item.item;
  }
}

排除重复选择

记录已选项目避免重复:

js实现选题

const allOptions = ['A','B','C','D','E'];
const selectedItems = new Set();

function getUniqueOption() {
  const available = allOptions.filter(x => !selectedItems.has(x));
  if (available.length === 0) return null;

  const choice = available[Math.floor(Math.random() * available.length)];
  selectedItems.add(choice);
  return choice;
}

可视化选择器

创建简单的UI选择器:

<div id="selector">
  <button data-option="1">选项1</button>
  <button data-option="2">选项2</button>
  <button data-option="3">选项3</button>
</div>
<script>
  document.querySelectorAll('#selector button').forEach(btn => {
    btn.addEventListener('click', () => {
      console.log(`选择了: ${btn.dataset.option}`);
    });
  });
</script>

抽奖转盘实现

使用CSS动画实现转盘效果:

function spinWheel(items, duration = 3000) {
  const wheel = document.getElementById('wheel');
  const degrees = 360 * 5 + Math.floor(Math.random() * 360);
  wheel.style.transition = `transform ${duration}ms cubic-bezier(0.17,0.89,0.32,0.98)`;
  wheel.style.transform = `rotate(${degrees}deg)`;

  setTimeout(() => {
    const segmentAngle = 360 / items.length;
    const offsetAngle = degrees % 360;
    const selectedIndex = Math.floor((360 - offsetAngle) / segmentAngle) % items.length;
    console.log('抽中:', items[selectedIndex]);
  }, duration);
}

这些实现方案覆盖了从基础随机选择到带权重的进阶选择,以及可视化交互的实现方式。根据具体需求可以选择合适的方案或组合使用多个方法。

标签: js
分享给朋友:

相关文章

js实现验证码

js实现验证码

实现验证码的JavaScript方法 生成随机验证码 使用Math.random()生成随机字符串,结合数字和字母: function generateCaptcha() { const cha…

使用js实现

使用js实现

使用JavaScript实现 JavaScript可以通过Math.random()函数生成随机数,结合其他方法可以实现多种随机数生成需求。 // 生成0到1之间的随机小数 const random…

vue实现js休眠

vue实现js休眠

实现 JavaScript 休眠的方法 在 Vue 中实现 JavaScript 休眠(延迟执行)可以通过以下方式实现。由于 JavaScript 本身没有内置的 sleep 函数,通常使用 Prom…

js实现vue路由

js实现vue路由

Vue 路由的基本实现 在 Vue.js 中实现路由功能通常使用 Vue Router 库。Vue Router 是 Vue.js 官方的路由管理器,用于构建单页面应用(SPA)。 安装 Vue R…

js实现正交

js实现正交

正交的概念 正交在数学和计算机科学中通常指两个向量垂直或线性无关。在编程中,正交性常被用于设计模块化、低耦合的系统。 向量正交判断 判断两个向量是否正交可以通过点积是否为0来实现: fun…