如何写随机代码
有时候写随机代码搞的很⿇烦,每次写都要想,下⾯是我常⽤的⼀些随机代码,有不⾜之处还望⼀扫⽽过的朋友给点新意。 1/2概率
let rand = 0.5-Math.random() > 0 ? true : false;
let rand = 1/3 - Math.random() > 0 ? true : false;
0-n 、1-n、m-n随机整数
let rand = Math.floor((n +1) * Math.random());//0=< rand <= n
let rand = Math.floor(1+n * Math.random());//1=< rand <= n
let rand = Math.floor(m+Math.floor((n-m+1)* Math.random()));//m=< rand <= n
let arr = [1,2,3,4,5,6,7,8,9,0];
arr.sort(()=>0.5-Math.random());
console.log(arr);//1, 5, 3, 2, 4, 6, 8, 7, 0, 9
随机数也可以通过getTime(),因为getTime()的最后⼏位是随机的
new Date().getTime()助板
硼硅酸盐玻璃15253986856762dj
new Date().getTime()
1525398692149
微波
烘箱new Date().getTime()
1525398707429
new Date().getTime()
1525398709308
new Date().getTime()
1525398710421
//
function getRandom(){
let x = new Date().getTime();
蓝牙手咪
let y = Math.floor(x/1000);
磁疗鞋return x - y*1000;
}