如何写随机代码

如何写随机代码
有时候写随机代码搞的很⿇烦,每次写都要想,下⾯是我常⽤的⼀些随机代码,有不⾜之处还望⼀扫⽽过的朋友给点新意。
1/2概率
let rand = 0.5-Math.random() > 0 ? true : false;
1/3、2/3概率(其他依次类推
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;
}

本文发布于:2024-09-21 10:41:49,感谢您对本站的认可!

本文链接:https://www.17tex.com/tex/4/125985.html

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。

标签:朋友   类推   数组   烘箱   蓝牙   新意   概率   排序
留言与评论(共有 0 条评论)
   
验证码:
Copyright ©2019-2024 Comsenz Inc.Powered by © 易纺专利技术学习网 豫ICP备2022007602号 豫公网安备41160202000603 站长QQ:729038198 关于我们 投诉建议