绝妙的函数:随机打乱数组
2018-10-10 本文已影响0人
喜欢唱歌的小狮子
Awesome Function: shuffle
原始数据:['红桃J', '黑桃A', '方块8', '梅花6', '黑桃K', '红桃A', '梅花9', '梅花2', '红桃K', '黑桃5']
方法一:数组数据两两交换
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
}
此方法在测试时踩了一个大坑,因为没有句尾分号,解构赋值的方括号与前一语句混在一起导致了报错,好一会检查不到错误之处,后来终于解决。
方法二:首尾取元素随机插入
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
}
方法三:简单随机抽样重组
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
}