本文通过实例代码给大家介绍了基于JavaScript实现微信抢红包功能,金额随机,额度在0.01和(剩余平均值*2)之间,具体的实例代码大家参考下本文
金额随机:额度在0.01和(剩余平均值*2)之间。
/** * 抢红包 * @param {[number]} totalAmount [总金额] * @param {[number]} totalPeople [总人数] * @return {[Array]} [每个人抢到的金额] */ function assign(totalAmount, totalPeople){ var remainAmount = +totalAmount; var remainPeople = +totalPeople; var arr = []; while(remainPeople > 0){ let num = scramble(remainAmount, remainPeople); remainAmount = remainAmount - num; remainPeople--; arr.push(num); } return arr; } function scramble(remainAmount, remainPeople){ if(remainPeople === 1){ return +remainAmount.toFixed(2); } let max = ((remainAmount / remainPeople) * 2 - 0.01).toFixed(2); let min = 0.01; let range = max - min; let rand = Math.random(); let num = min + Math.round(rand * range); //四舍五入 return num; }
总结
Atas ialah kandungan terperinci 如何利用JavaScript来实现微信抢红包功能的示例代码. Untuk maklumat lanjut, sila ikut artikel berkaitan lain di laman web China PHP!