js按照配置的概率生成,概率规则如下: 1------------50%
2------------30%
3------------15%
5------------5%
简单的代码
复杂点的
console.log(oArr);
// 计算总和
for (var i in oArr) {
sum += oArr[i][0];
}
// 思路就是如果设置的数落在随机数内,则返回,否则减去本次的数
for (var i in oArr) {
rand = Math.floor(Math.random()*sum + 1);
if (oArr[i][0] >= rand) {
result = oArr[i][0];
break;
} else {
sum -= oArr[i][0];
}
}
return result;
}
var oArr = {'5':[5,'Mac'],'3':[15,'iPhone'],'2':[30,'iPad'],'1':[50,'iWatch']};
console.log(prizeRand(oArr));