<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<script>
// 左闭右开 [0,1) 能取到0但是取不到1的一个随机小数
console.log(Math.random())
// 0~10之间的整数
console.log(Math.floor(Math.random() * 11))
// 随机数组
let arr = ['red', 'green', 'blue']
let random = Math.floor(Math.random() * arr.length)
console.log(random) //0,1,2
console.log(arr[random])
//取 N ~ M 的随机函数 直接套公式
function getRandom(N, M) {
return Math.floor(Math.random() * (M - N + 1)) + N
}
console.log(getRandom(4, 8))
</script>
</body>
</html>
07_随机数函数
最新推荐文章于 2024-09-14 18:52:56 发布
该代码示例展示了如何在JavaScript中生成随机数,包括[0,1)区间内的小数、0~10之间的整数,以及从给定数组中随机选取元素的方法。还定义了一个函数getRandom用于生成指定范围N~M内的随机整数。
摘要由CSDN通过智能技术生成