优化下边的方法const getRandData = list = 将percent值乘以100并转换为整数 const percentArray = listmapitem = itemexposurePer 计算所有数字的总和 const sum = percentArrayreduceacc val = acc + val 0 对数组进行归一化处理
const getRandData = (list) => { const percentArray = list.map((item) => item.exposurePer * 100); // 将percent值乘以100并转换为整数 const sum = percentArray.reduce((acc, val) => acc + val, 0); const normalizedArray = percentArray.map((val) => val / sum); const randomNumber = Math.floor(Math.random() * 100); let index = 0; let cumulative = 0; while (cumulative < randomNumber && index < normalizedArray.length) { cumulative += normalizedArray[index]; index++; } return list[index - 1]; }
// 优化后,将percent值乘以100并转换为整数,避免使用小数,提高计算精度。 // 同时,将sum变量的初始值设置为0,避免使用undefined,提高代码健壮性
原文地址: http://www.cveoy.top/t/topic/g0VQ 著作权归作者所有。请勿转载和采集!