概率的可配置化
function randomInProbability( weights ){ if( arguments.length > 1 ){ weights = [].slice.call( arguments ); } var total, current = 0, parts = [], i = 0, l = weights.length; total = weights.reduce ? weights.reduce( function( a, b ){ return a + b; } ) : eval( weights.join( '+' ) ); for( ; i < l; i ++ ){ current += weights[ i ]; parts.push( 'if( p < ', current / total, ' ) return ', i / l, ' + n;' ); } return Function( 'var p = Math.random(), n = Math.random() / ' + l + ';' + parts.join( '' ) ); } var updateRandom = randomInProbability( 0.01, 0.02, 0.09, 1.8, 0.1 ); var objects = [ '登山包', '旅行箱', '移动电源', '谢谢参与', '不中奖' ]; var randomIndex = Math.floor( objects.length * updateRandom() ); var object = objects[ randomIndex ];
php资料