js如何打乱一个数组让其元素随机化

function shuffle(arr) {
      for(let i = 0; i < arr.length; i++){
          let randomIndex = Math.floor(Math.random() * (i + 1))
          let item = arr[randomIndex]
          arr[randomIndex] = arr[i]
          arr[i] = item
      }
      return arr;
  }

  
  let arr = [1,2,3,4,5]
  console.log(shuffle(arr))

posted on 2022-03-28 22:00  GameCat  阅读(67)  评论(0编辑  收藏  举报

导航