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(),最终通过向下取整获得最近的整数。

 

posted @ 2019-06-10 21:25  风一样的man  阅读(4355)  评论(0)    收藏  举报