最近做了一个JavaScript按概率随机生成事件,于是整理了一下思路,写了一个小demo:
for(var i = arr2.length - 1; i >= 0; i--) {
sum += arr2[i]; // 统计概率总和
};
random *= sum; // 生成概率随机数
for(var i = arr2.length - 1; i >= 0; i--) {
factor += arr2[i];
if(random <= factor)
return arr1[i];
};
return null;
};
sum += arr2[i]; // 统计概率总和
};
random *= sum; // 生成概率随机数
for(var i = arr2.length - 1; i >= 0; i--) {
factor += arr2[i];
if(random <= factor)
return arr1[i];
};
return null;
};
// test
var a = ['mac','iphone','vivo','OPPO'];
var b = [0.1,0.2,0.3,0.4];
console.log(random(a,b));