<分区>
我在 js 中有这样的对象:
const Obj = [ {
propability: 0.5,
name: 'Item with propability 0.5%'
}, {
propability: 1,
name: 'Item with propability 1%'
}
];
有人知道如何为此创建算法吗?只是简单的代码。
我想按他的概率返回。
<分区>
我在 js 中有这样的对象:
const Obj = [ {
propability: 0.5,
name: 'Item with propability 0.5%'
}, {
propability: 1,
name: 'Item with propability 1%'
}
];
有人知道如何为此创建算法吗?只是简单的代码。
我想按他的概率返回。
最佳答案
如果我没理解错的话,你想要这样的东西:
const Obj = [
{
propability: 0.5,
name: 'Item with propability 0.5%'
},
{
propability: 5,
name: 'Item with propability 5%'
},
{
propability: 10,
name: 'Item with propability 10%'
},
{
propability: 0.0001,
name: 'Item with propability 0.0001%'
}
];
// get total probability
var total = 0;
for(let j in Obj){
total += Obj[j].propability;
}
//choose random obj
console.log(pick_random());
function pick_random(){
var pick = Math.random()*total;
for(let j in Obj){
pick -= Obj[j].propability;
if(pick <= 0){
return Obj[j];
}
}
}
关于javascript - 随性绘图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57132130/