闲言碎语不要讲,咱们直接上代码:
有什么讲的不对的地方,希望大家不吝赐教,感谢😊😊😊
let data = [{
weight: 20,
content: 'a'
}, {
weight: 40,
content: 'b'
}, {
weight: 30,
content: 'c'
}, {
weight: 10,
content: 'd'
}];
/** 总权重法 */
function getRandom() {
let sum = 0;
for (let i = 0; i < data.length; i++) {
sum += data[i].weight;
}
let random = Math.floor(Math.random() * sum);
console.log(random);
sum = 0;
for (let i = 0; i < data.length; i++) {
let weight = data[i].weight + sum;
if (random >= sum && random < weight) {
console.log(data[i]);
return data[i];
}
sum = weight;
}
}
/** 先写的有大权重,后写得分剩下的权重 */
function getRandom1() {
let random = Math.floor(Math.random() * 100);
console.log('random', random);
for (let i = 0; i < data.length; i++) {
if (random <= data[i].weight) {
return data[i];
} else {
random = Math.floor(Math.random() * 100);
}
}
return data[data.length - 1];
}
function getRandom2() {
let newData = [];
for (let i = 0; i < data.length; i++) {
let item = data[i];
for (let j = 0; j < item.weight; j++) {
newData.push(item);
}
}
let randomIndex = Math.floor(Math.random() * newData.length);
console.log(newData.length, randomIndex, newData[randomIndex]);
return newData[randomIndex];
}
来源:CSDN
作者:Simorel
链接:https://blog.csdn.net/Simoral/article/details/103909029