Ts/Js 实现抽奖功能--根据物品权重计算
/** * * @param vWeight 权重的数组:例如【1,1,1,1,1】 * @returns //注意:返回的下标加1(占第几个) */ public static GetPrize(vWeight: number[]): number { //计算权重之和 prev 是前一次累加后的数值,currVal 是本次待加的数值 let weightSum = vWeight.reduce((prev, currVal) => { return prev + currVal; }, 0); let random = Math.ceil(Math.random() * weightSum); console.log("random ---->" + random); let count = 0; for (let i = 0; i < vWeight.length; i++) { count += vWeight[i]; if (random <= count) { return i + 1; } } }
山重水复疑无路,柳暗花明又一村!
专注填坑,少走弯路!