获取随机数、浮点数取整方法

Math.(random/round/cell/floor)随机数的用法

Math.random()      返回值是一个大于等于0,且小于1的随机数

Math.random()*N    返回值是一个大于等于0,且小于N的随机数


Math.round()        四舍五入的取整

Math.ceil()            向上取整,如Math.cell(0.3)=1 、又如Math.ceil(Math.random()*10) 返回1~10

Math.floor()          向下取整,如Math.floor(0.3)=0、又如Math.floor(Math.random()*10)返回0~9

例:

Math.round(Math.random()*15)+5;  返回5~20随机数

Math.round(Math.random()*(y-x))+x;  返回x~y的随机数,包含负数。


假设arr存着54张牌,

用Math.floor(Math.random()*54)获取i,j,

然后arr[i]<=>arr[j]两个交换多次之后即可模拟实现随机洗牌的效果。

用9张牌举例:

let arr=[1,2,3,4,5,6,7,8,9]

for(let i = 0;i<5;i++){

    let m = Math.floor(Math.random()*9);

    let n = Math.floor(Math.random()*9);

    let t = arr[m];

    arr[m]=arr[n];

    arr[n]=t;

}

console.log(arr) //[8, 7, 3, 5, 4, 2, 6, 1, 9]   洗牌后会打乱了顺序

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容