绝妙的函数:随机打乱数组

Awesome Function: shuffle

在线演示

原始数据:[‘红桃J’, ‘黑桃A’, ‘方块8’, ‘梅花6’, ‘黑桃K’, ‘红桃A’, ‘梅花9’, ‘梅花2’, ‘红桃K’, ‘黑桃5’]

方法一:数组数据两两交换

1
2
3
4
5
6
7
8
9
const shuffle = array => {
let count = array.length - 1
while (count) {
let index = Math.floor(Math.random() * (count + 1))
;[array[index], array[count]] = [array[count], array[index]]
count--
}
return array
}

此方法在测试时踩了一个大坑,因为没有句尾分号,解构赋值的方括号与前一语句混在一起导致了报错,好一会检查不到错误之处,后来终于解决。

方法二:首尾取元素随机插入

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
const shuffle2 = array => {
let count = len = array.length
while (count) {
let index = Math.floor(Math.random() * len)
array.splice(index, 0, array.pop())
count--
}
return array
}



const shuffle2 = array => {
let count = len = array.length
while (count) {
let index = Math.floor(Math.random() * len)
array.splice(index, 0, array.shift())
count--
}
return array
}

方法三:简单随机抽样重组

1
2
3
4
5
6
7
8
9
10
11
const shuffle3 = array => {
let tempArr = Array.of(...array)
let newArr = []
let count = tempArr.length
while (count) {
let index = Math.floor(Math.random() * (count - 1))
newArr.push(tempArr.splice(index, 1)[0])
count--
}
return newArr
}