# 一. 基础
# 二. 实现
//先定义一个某数值范围内的随机数
function getRandom(min, max) {
return Math.floor(Math.random() * (max - min + 1) + min);
}
// 克隆数组方法
/**
* 克隆数组
* @param {array} arr 原数组
* @return {array} 新数组
*/
function cloneArr(arr) {
// 从第一个字符就开始 copy
// slice(start,end) 方法可从已有的数组中返回选定的元素。
return arr.slice(0);
}
//洗牌
function shuffle(arr, flag = false) {
// console.log('arr',arr)
let newArr = [];
flag ? (newArr = arr) : (newArr = cloneArr(arr));
for (let i = 0; i < newArr.length; i++) {
let j = getRandom(0, i);
let temp = newArr[i];
newArr[i] = newArr[j];
newArr[j] = temp;
}
// console.log('arr',arr,newArr)
return newArr;
}
//调用
shuffle(list); //list一般为数组对象
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
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
function shuffle(array) {
const length = array == null ? 0 : array.length
if (!length) {
return []
}
let index = -1
const lastIndex = length - 1
const result = copyArray(array)
while (++index < length) {
const rand = index + Math.floor(Math.random() * (lastIndex - index + 1))
const value = result[rand]
result[rand] = result[index]
result[index] = value
}
return result
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17