<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 发布