<script>
// 1.random()返回一个随机的小数 [0,1)
console.log(Math.random());
// 推导过程
// 获取0-10之间的数 [0,10)
// [0,1)*10 = [0,10)
console.log(Math.floor(Math.random()*10));
// 获取1-10之间的数 [0,10]
// [0,1)* 10 +1 = [1,10]
console.log(Math.floor(Math.random()*10 +1));
// 获取20-50之间的数 [20,50]
// [0,1)* (50-20+1) + 20= [20,50]
// 0 + 20 20
// 31 + 20 50
console.log(Math.floor(Math.random()*(50-20+1)+20));
// 2.得到两个数之间的随机整数 [min,max]
function getRandom(min,max){
return Math.floor(Math.random()*(max - min + 1)) + min;
}
console.log(getRandom(1,10));
// 3.随机点名
var arr = ['虞书欣','赵晓棠','安琦'];
console.log(arr[getRandom(0,arr.length - 1)]);
</script>
Math随机数
最新推荐文章于 2024-02-25 14:12:25 发布
这篇博客介绍了JavaScript中生成随机数的方法,包括如何生成指定范围内的整数。作者通过示例展示了如何使用Math.random()函数,并提供了一个自定义函数getRandom()来在两个数之间生成随机整数。此外,还展示了如何利用这些随机数进行随机点名的应用,例如从一个数组中随机选取名字。
946

被折叠的 条评论
为什么被折叠?



