JS随机打乱数组
function shuffle(arr) {
let _arr = arr.slice()
for (let i = 0; i < _arr.length; i++) {
let j = getRandomInt(0, i)
let t = _arr[i]
_arr[i] = _arr[j]
_arr[j] = t
}
return _arr
}
function getRandomInt(min, max) {
return Math.floor(Math.random() * (max - min + 1) + min)
}
1
2
3
4
5
6
7
8
9
10
11
12
13
<html>
原数组:<span id="span1"></span>
<button id="btn">click me!打乱数组</button> </br></br>
打乱结果:<span id="span2"></span>
</html>
<script>
function getRandomInt(min, max) {
return Math.floor(Math.random() * (max - min + 1) + min)
}
function shuffle(arr) {
let _arr = arr.slice()
for (let i = 0; i < _arr.length; i++) {
let j = getRandomInt(0, i)
let t = _arr[i]
_arr[i] = _arr[j]
_arr[j] = t
}
return _arr
}
function $(el){
return document.querySelector(el)
}
let arr = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
const $span2 = $('#span2');
$('#span1').textContent = arr;
$('#btn').onclick = function () {
$span2.textContent = shuffle(arr);
}
</script>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33