这种逻辑应该后台写,并且在提交中奖结果时要进行验证,否则前端太容易篡改数据了。
点击抽奖时,请求后台
后台返回抽奖结果
前端播放抽奖动画,并且保证最后停在返回的中奖结果项上
--- 更新 ---
大致给你个权重算法
// 权重越小越难中奖
// 这里iphone中奖概率为 1/2001 大致为 0.000499
const prizeList = [
{ name: 'iphone', weight: 1 },
{ name: 'book', weight: 1000 },
{ name: 'sorry', weight: 1000 }
]
function config (prizeList) {
let index = 0
prizeList.forEach(prize => {
prize.min = index
prize.max = index + prize.weight
index += prize.weight
})
return function () {
let num = random(0, index - 1)
return prizeList.filter(prize => prize.max > num && prize.min <= num)[0]
}
}
// test
function test (total, prizeName) {
const lottery = config(prizeList)
let n = 0
for (let i = 0; i < total; i++) {
if (lottery().name === prizeName) {
n++
}
}
console.log(prizeName, n / total)
}
test(100000, 'iphone') // iphone 0.00047
test(100000, 'book') // book 0.50047