在Javascript文件上执行基于random()的不同函数

我的网站调用一个js文件(名为file.js ),如下所示:

<script src="urltothefile/file.js"></script> 

.js文件本身以random()函数开始,如果数字低于50,它应该打印出“Nothing here to see”,如果它更高,它应该执行一个javascript代码。

可以这样做吗?

Math.random() * 100返回0到100之间的数字。

 if (Math.random() * 100 > 50) { alert('nothing here to see'); } else { // Do the code.. } 

你可能想创build一个function。 就像是…

 function prob(value){ if(value < 0 || value > 1) throw "Value should be between 0 and 1."; return Math.random() < value; } if(prob(.5)) { //do something //note: i prefer this inverted logic } else { alert('nothing here to see'); }