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