Math.random() 静态方法返回一个大于等于 0 且小于 1 的伪随机浮点数,并在该范围内近似均匀分布。
生成N~M之间的整数(包含N和M):
Math.floor(Math.random() * (M - N + 1)) + N
示例:生成0~1之间的一个随机数
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<script>
console.log(Math.random())
</script>
</body>
</html>
控制台输出:
示例:生成0~10之间的整数,包含0和10
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<script>
console.log(Math.floor(Math.random() * (10 + 1)))
</script>
</body>
</html>
一次运行输出:
从数组中随机获取一个元素
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<script>
let arr = ['red', 'green', 'blue']
let random = Math.floor(Math.random() * arr.length)
console.log(arr[random])
</script>
</body>
</html>
一次运行输出:
生成5~10(包含5和10)之间的整数
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<script>
console.log(Math.floor(Math.random() * (5 + 1)) + 5)
</script>
</body>
</html>
一次运行输出:
示例:生成N~M之间的整数(包含N和M)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<script>
function getRandom(N, M) {
return Math.floor(Math.random() * (M - N + 1)) + N
}
console.log(getRandom(4, 8))
</script>
</body>
</html>
一次运行输出: