抽签js实现
抽签功能实现
使用JavaScript实现抽签功能可以通过数组存储选项,随机选择其中一个元素。以下是几种常见的实现方式:
基础数组抽签
const drawLottery = (items) => {
const randomIndex = Math.floor(Math.random() * items.length);
return items[randomIndex];
};
// 使用示例
const prizes = ['一等奖', '二等奖', '三等奖'];
const result = drawLottery(prizes);
console.log(result); // 随机输出其中一个奖项
带权重的抽签
如果需要不同选项有不同的中奖概率,可以使用权重系统:
const weightedDraw = (items, weights) => {
let totalWeight = weights.reduce((a, b) => a + b, 0);
let random = Math.random() * totalWeight;
let weightSum = 0;
for (let i = 0; i < items.length; i++) {
weightSum += weights[i];
if (random <= weightSum) return items[i];
}
};
// 使用示例
const options = ['苹果', '香蕉', '橙子'];
const probabilities = [0.5, 0.3, 0.2]; // 对应50%, 30%, 20%概率
const result = weightedDraw(options, probabilities);
不重复抽签
确保每次抽签结果不重复,直到所有选项被抽完:
class UniqueDraw {
constructor(items) {
this.items = [...items];
this.remaining = [...items];
}
draw() {
if (this.remaining.length === 0) {
this.remaining = [...this.items];
}
const randomIndex = Math.floor(Math.random() * this.remaining.length);
const result = this.remaining[randomIndex];
this.remaining.splice(randomIndex, 1);
return result;
}
}
// 使用示例
const drawer = new UniqueDraw(['A', 'B', 'C', 'D']);
console.log(drawer.draw()); // 随机不重复输出
可视化抽签效果
添加动画效果增强用户体验:
function animateDraw(selector, items, duration = 3000) {
const element = document.querySelector(selector);
let startTime = Date.now();
const animate = () => {
const elapsed = Date.now() - startTime;
const progress = Math.min(elapsed / duration, 1);
// 快速切换显示不同选项
const tempIndex = Math.floor(Math.random() * items.length);
element.textContent = items[tempIndex];
if (progress < 1) {
requestAnimationFrame(animate);
} else {
// 最终结果
const finalIndex = Math.floor(Math.random() * items.length);
element.textContent = items[finalIndex];
}
};
animate();
}
// 使用示例
// animateDraw('#result', ['选项1', '选项2', '选项3']);
实际应用示例
结合HTML创建一个完整的抽签界面:

<div id="lottery">
<h3>今日幸运水果</h3>
<div id="result">点击开始抽签</div>
<button onclick="startDraw()">开始抽签</button>
</div>
<script>
const fruits = ['🍎', '🍌', '🍊', '🍉', '🍇', '🍓'];
function startDraw() {
const resultElement = document.getElementById('result');
resultElement.textContent = '抽签中...';
setTimeout(() => {
const winner = fruits[Math.floor(Math.random() * fruits.length)];
resultElement.textContent = winner;
}, 1000);
}
</script>
这些实现方式涵盖了从基础到进阶的抽签功能,可以根据具体需求选择适合的方案。权重系统适合需要控制不同选项概率的场景,而不重复抽签则适用于需要确保所有选项都会被选中的情况。






