假设我们有日期:
var datas = [{animal:"chicken"}, {animal: "cow"}, {animal: "duck"}];
var after_massage = [];
datas.forEach(function(key){
after_massage.push({animal: key.animal}, {percentage: randomPercent(); })
})
现在我不知道如何给每个对象分配随机百分比,并且三个对象的总和不能超过100%
最佳答案
您可以通过跟踪您的随机数可以达到的最大数然后继续递减来实现此目的。从理论上讲,这可以无限进行:
var datas = [{animal:"chicken"}, {animal: "cow"}, {animal: "duck"}];
var after_massage = [];
var max = 1;
var getRandomPercent = function(max) {
var percentage = Math.random() * (max - 0) + 0;
// every time we generate a random number, we'll decrement
max = max - percentage;
return percentage;
}
datas.forEach(function(key){
after_massage.push({animal: key.animal, percentage: getRandomPercent(max) })
});
console.log(after_massage);
见JSFiddle