let testArr = ['a', 'b', 'c', 'd', 'e', 'f', 'g']
1.直接使用for循环配合Math对象
disorderArray (arr) {
for (let i = 0; i <= arr.length - 1; i++) {
let randomIndex = Math.round(Math.random() * i)
let temp = arr[randomIndex]
arr[randomIndex] = arr[i]
arr[i] = temp
}
return arr
}
console.log(disorderArray(testArr))
2.使用forEach(for...in...或者for...of...)循环配合Math对象
disorderArray (arr) {
arr.forEach((value, index, array) => {
let randomIndex = Math.round(Math.random() * index)
let temp = array[randomIndex]
array[randomIndex] = array[index]
array[index] = temp
/**
* 注意此处的array[index]不能用value替代,原因在于只是改变了元素的指向;而没有改变arr中的元素
*/
})
return arr
}
console.log(disorderArray(testArr))
3.直接使用sort方法
const disorderArray = testArr.sort(function() {
return Math.random() > 0.5 ? -1 : 1
})
console.log(disorderArray)
4.尝试使用reduce方法(麻烦点,熟练下reduce)
const disorderArray = (arr) => {
let tempNum = arr.length
let otherArr = [...arr]
let tempCode = null
let tempArr = arr.reduce((acc, val, ind, array) => {
function getRandom() {
tempCode = Math.floor(Math.random() * tempNum)
return otherArr[tempCode]
}
let curVal = getRandom()
// 每次获取到数据之后,就减小index,并将otherArr中的一项删除
tempNum--
otherArr.splice(tempCode, 1)
return [...acc, curVal]
}, [])
return tempArr
}
console.log(disorderArray(testArr))