Home  >  Article  >  Web Front-end  >  Sample code for how to use JavaScript to implement the red envelope grabbing function on WeChat

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

黄舟
黄舟Original
2017-07-20 16:37:312722browse

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!

Statement:
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