直接通过数组中prob值来控制概率,值越大概率越高,值越小,概率越低
下面直接上实例代码
<!doctype html> <html> <head> <meta charset="utf-8"> <title>js概率算法实例</title> </head> <body> <script> function getRand(obj) { this.obj = obj; return this.init(); } //获取几率总和 getRand.prototype.sum = function(key) { var self = this; var obj = this.obj; var sum = 0; for (var i in obj) { sum += obj[i][key]; } return sum; }; //取得结果 getRand.prototype.init = function() { var result = null; var self = this; var obj = this.obj; var sum = this.sum('prob'); //几率总和 for (var i in obj) { var rand = parseInt(Math.random() * sum); if (rand <= obj[i].prob) { result = obj[i]; break; } else { sum -= obj[i].prob; } } return result; }; //几率数组 var obj = [{ name: '结果一', prob: 1 }, { name: '结果二', prob: 5 }, { name: '结果三', prob: 39 }, { name: '结果四', prob: 60 }, { name: '结果五', prob: 703 }, ]; //使用方法 // $result = new getRand(obj); //测试数据,循环1000次取得每个数据出现的次数 var record = []; for (var i = 0; i <= 100; i++) { var result = new getRand(obj); var index = false; for (var j in record) { if (record[j].name == result['name']) { index = j; document.write("第"+i+"次,"+record[j].name+"<br>"); break; } } if (index !== false) { record[index].num += 1; } else { record.push({ name: result['name'], num: 1 }); } } </script> </body> </html>