2014-02-28 42 views

回答

6

很简单,使用Math.random得到0和1之间的数字,并将其与0.02或真实速度/假你正在寻找。

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/random

的的Math.random()函数的范围在[0返回浮点,伪随机数,1),是从0(含)直到但不包括1 (独家),然后您可以缩放到您想要的范围。

因此,基本上:

var randomizer = function() { 
    return Math.random() > 0.02; 
}; 

编辑

如果你想让它更漂亮,您可以包在一个对象此功能,并设置有真正的比率/假。

var randomizer = { 
    _ratio: 0.02, // default ratio 
    setRatio: function (falses, total) { 
     this._ratio = falses/total; 
    }, 
    getResult: function() { 
     return Math.random() > this._ratio; 
    } 
}; 

然后

randomizer.getResult(); 
randomizer.setRatio(60, 1000); // 60 out of 10000 
+1

使事情更具可配置性:var randomizer = function(n,total){return Math.random()>(n/total); }; // randomizer(50,1000)',甚至'var createRandomizer(n,total){return function(){return Math。random()>(n/total); }; }; // var randomizer = createRandomizer(50,1000); randomizer();' – Prusse

+1

是的,在我的情况下,我会创建一个可配置速率的对象。 – bgusach

+0

感谢非评论性downvote。对此,我真的非常感激。 – bgusach

0

如何

赔率:50/1000 = 1/20

//Get random number from 1 to 20, if equals 20 return false 
if (Math.floor((Math.random()*20)+1) == 20) 
{ 
    return false; 
} 
else{ 
    return true; 
} 
0
function foo() { return Math.random() > 0.02; } 

// 1/50 == 0.02, so if it's less than 0.02 return false 
0

创建的随机数的每个所述功能运行时,在1和50之间:

var num = Math.floor((Math.random()*50)+1); 

然后,如果该数目等于50,用于例如,返回false。

0

随着Math.random,你可以达到你想要的东西:

function suchRandom(chanceInPercent){ 
    return Math.random() > chanceInPercent/100; 
} 

console.log(suchRandom(2)); //because 1000/50 = 20 true/1000 calls = 2% 

约20:http://jsfiddle.net/Ru7qY/1/

0

计数器....:d

var c = 0; 
function f() 
{ 
    return ++c % 50 == 0 ? false : true; 
} 
+0

非常有趣的“随机”概念xD – bgusach

+0

@ ikaros45是的,我知道'Math.random'是什么,我只是试图得到不同的答案,当我发布这个,有一些帖子'Math.random'解决方案;) –

+0

它不是'Math.random',而是随机的概念。你的功能不是随机的,而是可预测的。 – bgusach

1
function mostlyFalse() { 
    return Math.random() <= 0.05;  
} 

的jsfiddle随机显示大多'true',但偶尔'false':http://jsfiddle.net/t8E6t/1/

+1

该函数应该被称为'mostlyFalse' = ) – bgusach

+0

感谢您的提示 –