js实现选题
实现选题功能的JavaScript方法
基础实现方案
使用数组存储选项,通过随机索引选取:
const options = ['选项A', '选项B', '选项C', '选项D'];
const randomIndex = Math.floor(Math.random() * options.length);
const selected = options[randomIndex];
console.log(selected);
权重选择实现
为选项添加权重比例:

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;
}
}
排除重复选择
记录已选项目避免重复:

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






