数组乱序的错误方法及详解请浏览 参考链接 https://www.h5jun.com/post/array-shuffle.html

Fisher–Yates Shuffle

关于数组乱序,正确的解法应该是 Fisher–Yates Shuffle,复杂度 O(n)。其实它的思想非常的简单,遍历数组元素,将其与之前的任意元素交换。

function shuffle(a) {
  var length = a.length;
  var shuffled = Array(length);

  for (var index = 0, rand; index < length; index++) {
    rand = ~~(Math.random() * (index + 1));
    if (rand !== index) 
      shuffled[index] = shuffled[rand];
    shuffled[rand] = a[index];
  }

  return shuffled;
}