Home > Article > Web Front-end > Sample code for how to use JavaScript to implement the red envelope grabbing function on WeChat
This article introduces to you the function of grabbing red envelopes on WeChat based on JavaScript through example code. The amount is random and the amount is between 0.01 and (remaining average * 2). For the specific example code, please refer to this article
The amount is random: the amount is between 0.01 and (remaining average * 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; }
Summary
The above is the detailed content of Sample code for how to use JavaScript to implement the red envelope grabbing function on WeChat. For more information, please follow other related articles on the PHP Chinese website!