抽签js实现
抽签功能实现方法
基础抽签功能
使用JavaScript数组和随机数生成器实现简单抽签功能。准备一个包含选项的数组,通过随机索引选取其中一个元素。
function simpleDraw(names) {
const randomIndex = Math.floor(Math.random() * names.length);
return names[randomIndex];
}
const candidates = ['张三', '李四', '王五'];
console.log(simpleDraw(candidates));
权重抽签实现
当不同选项有不同权重时,可以使用累加权重的方法实现加权随机选择。先计算总权重,再根据随机数落在的区间决定选择哪个选项。
function weightedDraw(items) {
let totalWeight = items.reduce((sum, item) => sum + item.weight, 0);
let random = Math.random() * totalWeight;
let weightSum = 0;
for (const item of items) {
weightSum += item.weight;
if (random <= weightSum) return item.value;
}
}
const weightedItems = [
{value: '一等奖', weight: 1},
{value: '二等奖', weight: 3},
{value: '三等奖', weight: 6}
];
console.log(weightedDraw(weightedItems));
不重复抽签实现
需要从候选列表中抽取多个不重复的选项时,可以每次抽取后将该选项从数组中移除。
function uniqueDraw(names, count) {
const result = [];
const tempNames = [...names];
while (result.length < count && tempNames.length > 0) {
const randomIndex = Math.floor(Math.random() * tempNames.length);
result.push(tempNames[randomIndex]);
tempNames.splice(randomIndex, 1);
}
return result;
}
const students = ['小明', '小红', '小刚', '小丽'];
console.log(uniqueDraw(students, 2));
可视化抽签效果
结合HTML实现可视化抽签效果,包含动画和结果显示。
<div id="result"></div>
<button onclick="startDraw()">开始抽签</button>
<script>
function startDraw() {
const names = ['选项1', '选项2', '选项3', '选项4'];
const resultEl = document.getElementById('result');
let counter = 0;
const interval = setInterval(() => {
resultEl.textContent = names[Math.floor(Math.random() * names.length)];
counter++;
if(counter > 10) {
clearInterval(interval);
resultEl.textContent = simpleDraw(names);
}
}, 100);
}
</script>
注意事项
Math.random()生成的随机数在密码学上不安全,不适合安全敏感场景。前端实现应考虑防作弊机制,重要抽签建议在后端完成。多次抽签时注意性能问题,大数据集应考虑更高效的算法实现。







