Home > Web Front-end > JS Tutorial > body text

Sample code for how to use JavaScript to implement the red envelope grabbing function on WeChat

黄舟
Release: 2017-07-20 16:37:31
Original
2724 people have browsed it

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;
}
Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!