Jsは重み確率の値を取ることを実現します.
925 ワード
/**
* js
* @param Array arr js , [Object,Object,Object……]
* @return Array , percent/ percent , Object
* @author andyzhou
*/
function get_weight_random(arr){
// arr percent ,
/*
var arr = [{
name : '1',
percent : 1
}, {
name : '2',
percent : 2
}, {
name : '3',
percent : 1
}, {
name : '4',
percent : 2
}
];
*/
var total = 0;
var i, j, percent;
//
var index = new Array();
for (i = 0; i < arr.length; i++) {
// , , 100
percent = 'undefined' != typeof(arr[i].percent) ? parseInt(arr[i].percent*100) : 0;
for (j = 0; j < percent; j++) {
index.push(i);
}
total += percent;
}
//
var rand = Math.floor(Math.random() * total);
return arr[index[rand]];
}