繁体   English   中英

在Javascript文件上基于random()执行不同的功能

[英]Execute different function based on random() on Javascript file

我的网站像这样调用一个js文件(名为file.js ):

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

.js文件本身以random()函数开头,如果该数字小于50,它将打印“什么都看不到”,如果数字更大,则应执行javascript代码。

能做到吗?

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

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

您可能要创建一个函数。 就像是...

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');
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM