码迷,mamicode.com
首页 > 其他好文 > 详细

红包金额随机数的生成

时间:2017-07-12 18:53:37      阅读:115      评论:0      收藏:0      [点我收藏+]

标签:www   item   java   erro   ++   val   class   get   span   

 <form>
红包个数:<input type="text" name="count" id="count" required style="height: 20px;"> <br>
总金额(元):<input type="text" name="amount" id="amount" required style="height: 20px;"><br>
<input type="button" id="submit" value="获取红包金额">
</form></p>

<div id=‘result‘></div>

<script src="https://www.lijinma.com/javascripts/libs/jquery.min.js"></script>
<script>

$(#submit).click(function(){
  function getRandomInt(min, max) {
    return Math.floor(Math.random() * (max - min)) + min;
  }

  function getNextItemKey(currentKey, count) {
    if (currentKey > count) {
      throw Error: currentKey > count;
    }
    if (currentKey != count) {
      return currentKey + 1;
    } else {
      return 1;
    }
  }
  
  var count = $(#count).val();
  var amount = $(#amount).val();
  if (!count) {
    alert(红包个数必须填写);
    return false;
  }
  if (!amount) {
    alert(总金额必须填写);
    return false;
  }
  if (amount / count < 0.01) {
    alert(单个红包金额不可低于0.01元,请重新填写金额);
    return false;
  }
  amount = amount * 100;
  var items = [];
  for (var i = 0; i < count; ++ i) {
    items[i] = getRandomInt(1, 100);
  }
  var itemAmounts = [];
  var sum = items.reduce(function(pv, cv) { return pv + cv; }, 0);
  var currentAmount = 0;
  for (var i = 0; i < count; ++ i) {
    if (i !== count - 1) {
      itemAmounts[i] = Math.floor(items[i] / sum * amount);
      currentAmount += itemAmounts[i];
    } else {
      itemAmounts[i] = amount - currentAmount
    }
  }
  
  for (var i = 0; i < count; ++ i ) {
    if (itemAmounts[i] > 0) {
      continue;
    }
    var nextKey = getNextItemKey(i, count);
    var diff = 1 - itemAmounts[i];
    itemAmounts[i] = 1;
    itemAmounts[nextKey] -= diff;
  }
  
  for (var i = 0; i < count; ++ i ) {
    itemAmounts[i] = itemAmounts[i] / 100;
  }
  
  alert(itemAmounts.join()+);
  
});
</script>

 

红包金额随机数的生成

标签:www   item   java   erro   ++   val   class   get   span   

原文地址:http://www.cnblogs.com/dwb91/p/7156777.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!