左闭又开html
因此Math.floor(Math.random()*10); //可均衡获取0到9的随机整数。dom
Math.floor(Math.random()*max)+1;
Math.ceil(); //向上取整。函数
Math.floor(); //向下取整。学习
Math.round(); //四舍五入。spa
Math.random(); //0.0 ~ 1.0 之间的一个伪随机数。【包含0不包含1】 //好比0.8647578968666494code
Math.ceil(Math.random()*10); // 获取从1到10的随机整数 ,取0的几率极小。htm
Math.round(Math.random()); //可均衡获取0到1的随机整数。blog
Math.floor(Math.random()*10); //可均衡获取0到9的随机整数。get
Math.round(Math.random()*10); //基本均衡获取0到10的随机整数,其中获取最小值0和最大值10的概率少一半。it
由于结果在0~0.4 为0,0.5到1.4为1...8.5到9.4为9,9.5到9.9为10。因此头尾的分布区间只有其余数字的一半。
函数功能:生成[n,m]的随机整数。
在js生成验证码或者随机选中一个选项时颇有用。。
//生成从minNum到maxNum的随机数 function randomNum(minNum,maxNum){ switch(arguments.length){ case 1: return parseInt(Math.random()*minNum+1,10); break; case 2: return parseInt(Math.random()*(maxNum-minNum+1)+minNum,10); break; default: return 0; break; } }
Math.random()生成[0,1)的数,因此
Math.random()*5生成{0,5)的数。
一般指望获得整数,因此要对获得的结果处理一下。
parseInt(),Math.floor(),Math.ceil()和Math.round()均可获得整数。
parseInt()和Math.floor()结果都是向下取整。
因此Math.random()*5生成的都是[0,4] 的随机整数。
因此生成[1,max]的随机数,公式以下:
// max - 指望的最大值 parseInt(Math.random()*max,10)+1; Math.floor(Math.random()*max)+1; Math.ceil(Math.random()*max);
因此生成[0,max]到任意数的随机数,公式以下:
// max - 指望的最大值 parseInt(Math.random()*(max+1),10); Math.floor(Math.random()*(max+1));
因此但愿生成[min,max]的随机数,公式以下:
// max - 指望的最大值 // min - 指望的最小值 parseInt(Math.random()*(max-min+1)+min,10); Math.floor(Math.random()*(max-min+1)+min);
本文做者starof,因知识自己在变化,做者也在不断学习成长,文章内容也不定时更新,为避免误导读者,方便追根溯源,请诸位转载注明出处:http://www.cnblogs.com/starof/p/4988516.html有问题欢迎与我讨论,共同进步。