js实现抽签
实现抽签功能的JavaScript方法
基础数组随机抽取
使用Math.random()生成随机数,结合数组索引实现简单抽签:
const names = ['张三', '李四', '王五', '赵六'];
const randomIndex = Math.floor(Math.random() * names.length);
const winner = names[randomIndex];
console.log(`中签者: ${winner}`);
权重抽签算法
为每个选项添加权重属性,实现加权随机抽取:
function weightedDraw(items) {
const totalWeight = items.reduce((sum, item) => sum + item.weight, 0);
let random = Math.random() * totalWeight;
for (const item of items) {
random -= item.weight;
if (random <= 0) return item;
}
}
const candidates = [
{ name: '张三', weight: 10 },
{ name: '李四', weight: 30 },
{ name: '王五', weight: 60 }
];
console.log(weightedDraw(candidates));
不重复抽签实现
使用Set记录已抽中结果,避免重复抽取同一选项:
class UniqueDraw {
constructor(items) {
this.items = [...items];
this.drawn = new Set();
}
draw() {
const available = this.items.filter(item => !this.drawn.has(item));
if (available.length === 0) return null;
const randomIndex = Math.floor(Math.random() * available.length);
const result = available[randomIndex];
this.drawn.add(result);
return result;
}
}
const drawSystem = new UniqueDraw(['A', 'B', 'C', 'D']);
console.log(drawSystem.draw());
console.log(drawSystem.draw());
可视化抽签动画
结合DOM操作实现可视化抽签效果:
function animateDraw(elementId, options, duration = 3000) {
const element = document.getElementById(elementId);
let startTime = Date.now();
const interval = 50;
const timer = setInterval(() => {
const elapsed = Date.now() - startTime;
const progress = Math.min(elapsed / duration, 1);
const randomIndex = Math.floor(Math.random() * options.length);
element.textContent = options[randomIndex];
if (progress >= 1) {
clearInterval(timer);
const finalIndex = Math.floor(Math.random() * options.length);
element.textContent = `最终结果: ${options[finalIndex]}`;
}
}, interval);
}
// 使用示例: animateDraw('drawResult', ['选项1', '选项2', '选项3']);
概率分布验证
测试抽签算法的概率分布是否合理:

function testDistribution(drawFunc, iterations = 10000) {
const resultMap = new Map();
for (let i = 0; i < iterations; i++) {
const result = drawFunc();
resultMap.set(result, (resultMap.get(result) || 0) + 1);
}
console.log('概率分布测试结果:');
for (const [key, count] of resultMap) {
console.log(`${key}: ${(count / iterations * 100).toFixed(2)}%`);
}
}
// 示例用法
testDistribution(() => {
const items = ['A', 'B', 'C'];
return items[Math.floor(Math.random() * items.length)];
});
这些方法涵盖了从基础到进阶的抽签功能实现,可根据实际需求选择适合的方案或组合使用。可视化抽签适合网页应用,权重算法适合需要控制中签概率的场景,不重复抽签则适用于需要确保唯一性的情况。






