使用js對數組進行亂序排列

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)


參考文章:Math.round(),Math.ceil(),Math.floor()的區別https://www.cnblogs.com/johnsonwei/p/6101171.html

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章