JsWeb前端之路程序员

JavaScript随机打乱数组排序的几个方法

2018-04-02  本文已影响33人  ITgecko

前言

一个不太好的实现
function getRandom (arr) {
  let dp = [...arr]
  let result = []
  while (dp.length > 0) {
    let randomIndex = Math.floor(Math.random() * (dp.length))
    result.push(dp.splice(randomIndex, 1)[0])
  }
  return result
}
一个抖机灵的实现
function getRandom (arr) {
    let dp = [...arr]
    return dp.sort(() => Math.random() < .5)
}
Fisher–Yates shuffle
function shuffle (arr) {
  let res = [...arr]
  for (let i = arr.length - 1; i > 0; i--) {
    let randomIndex = Math.floor(Math.random() * (i + 1))
    let randomItem = res[randomIndex]
    res[randomIndex] = res[i]
    res[i] = randomItem
  }
  return res
}
上一篇 下一篇

猜你喜欢

热点阅读