js实现抽签
实现抽签功能的方法
使用Math.random()生成随机数
const participants = ['张三', '李四', '王五', '赵六'];
const winner = participants[Math.floor(Math.random() * participants.length)];
console.log('中奖者:', winner);
使用Fisher-Yates洗牌算法
这种方法适合需要抽取多个获奖者的情况:

function shuffleArray(array) {
for (let i = array.length - 1; i > 0; i--) {
const j = Math.floor(Math.random() * (i + 1));
[array[i], array[j]] = [array[j], array[i]];
}
return array;
}
const shuffled = shuffleArray([...participants]);
const winners = shuffled.slice(0, 3); // 抽取3个获奖者
console.log('获奖者:', winners);
使用ES6的扩展运算符
const randomParticipant = arr => arr[Math.floor(Math.random() * arr.length)];
console.log('随机抽中:', randomParticipant(participants));
带有动画效果的抽签实现
function drawWithAnimation(names, duration = 3000) {
let start = Date.now();
let timer = setInterval(() => {
let timePassed = Date.now() - start;
let randomIndex = Math.floor(Math.random() * names.length);
console.clear();
console.log('抽签中...', names[randomIndex]);
if (timePassed >= duration) {
clearInterval(timer);
console.log('最终结果:', names[randomIndex]);
}
}, 100);
}
drawWithAnimation(participants);
注意事项
- 确保参与者列表不为空
- 对于重要抽奖,应考虑使用更安全的随机数生成方法
- 可以添加去重逻辑防止重复中奖
- 考虑将结果保存到数据库或日志中
这些方法可以根据具体需求进行组合和扩展,例如添加排除已中奖人员、设置不同中奖概率等功能。






