首先上代码:
<!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>
<script>
function getRandom(min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
console.log(getRandom(3, 6));
</script>
</head>
<body>
</body>
</html>
首先看最里面那一层Math.random()会产生一个[0,1)之间的小数,然后乘以(max-min+1)就会产生一个[0,max-min+1)之间的小数,外层是一个Math.floor()内置函数,这个函数是向下取整函数。比如1.2->1 1.6->1。
拿min=3,max=6举例:
Math.floor(Math.random()*(max-min+1))相当于执行Math.floor(Math.random()*4),相当于会得到值0 1 2 3 ,然后加上min=3就会可能得到值3 4 5 6。
如果不进行加1的话就可能得到的值就是3 4 5就取不到最大值,所以这里必须加1。