使用js完成数组乱序排列

本文介绍四种不同的数组乱序算法实现,包括使用for循环配合Math对象、forEach循环、sort方法及reduce方法,每种方法均有详细代码示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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))


参考文章:Math.round(),Math.ceil(),Math.floor()的区别https://www.cnblogs.com/johnsonwei/p/6101171.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值