JavaScript 使用random()生成随机数

function myFunction() {

var a =Math.floor(Math.random()*10);
return a;
}

// 

记住 Math.random() 永远不会返回 1。同时因为我们是在用 Math.floor() 向下取整,所以最终我们获得的结果不可能有 20。这确保了我们获得了一个在0到19之间的整数。

把操作连缀起来,代码类似于下面:

Math.floor(Math.random() * 20);

我们先调用 Math.random(),把它的结果乘以20,然后把上一步的结果传给 Math.floor(),最终通过向下取整获得最近的整数。

转载于:https://www.cnblogs.com/chendi618/p/11000360.html

猜你喜欢

转载自blog.csdn.net/weixin_33754913/article/details/93234291