方法1: 利用中间变量重新赋值
let arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 0]
arr.forEach((item, index) => {
// 取随机数作为随机数组下标
const randomIndex = parseInt(Math.random() * arr.length)
// 定义中间变量保存随机下标对应的值
let x = arr[randomIndex]
// 将循环内当前项赋值给数组对应随机下标的值
arr[randomIndex] = arr[index]
// 将中间变量储存的随机下标对应的值赋值给循环内当前项
arr[index] = x
})
console.log(arr)
方法2: 利用数组的 length 属性
var arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 0]
var newArr = []
// 当原数组长度为 0 时终止循环
while (arr.length > 0) {
// 取随机数作为下标
const randomIndex = parseInt(Math.random() * arr.length)
// 将随机下标的值添加到新数组
newArr.push(arr[randomIndex])
// 将随机下标的值在原数组中删除以减少原数组长度
arr.splice(randomIndex, 1)
}
console.log(newArr)