获取两个数字之间的随机数以及如何打乱数组

Math.random()可以获取到0到1之间的随机数,但是要获取指定值之间的任意数值的话就需要一定的数学计算了,下面是代码存档

1
2
3
4
5
6
function test(min,max) {
document.writeln(Math.floor(Math.random() * (max - min + 1) +min));
};
setInterval(() => {
test(1,100);
},100);

点击这里查看demo

拓展1、 高效打乱数组的方法

1
2
3
function shuffle(arr) {
arr.sort(() => Math.random() - 0.5);
}

拓展2、 打乱数组的方法

上面的方法并不是真随机打乱数组,每个元素仍然有很大机率在它原来的位置附近出现。详见这里

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
function getRandom(min, max) {
return Math.floor(Math.random() * (max - min + 1) +min);
}
function shuffle(arr) {
for (let i = 0; i < arr.length; i++) {
let temp = getRandom(0, i);
let t = arr[i];
arr[i] = arr[temp];
arr[temp] = t;
}
return arr;
}
let arr = [];
for (var i = 0; i <= 10; i++) {
arr[i] = i;
}
console.log(shuffle(arr));

es6的实现

1
2
3
4
5
6
7
function shuffle(arr) {
let i = arr.length;
while (i) {
let j = Math.floor(Math.random() * i--);
[arr[j], arr[i]] = [arr[i], arr[j]];
}
}

获取两个数字之间的随机数以及如何打乱数组
https://xypecho.github.io/2018/05/03/获取两个数字之间的随机数/
作者
很青的青蛙
发布于
2018年5月3日
许可协议