front-end-interview icon indicating copy to clipboard operation
front-end-interview copied to clipboard

随机数(洗牌算法)

Open Liqiuyue9597 opened this issue 4 years ago • 1 comments

将一个有序的数组打乱,要求随机。

Liqiuyue9597 avatar Sep 28 '20 03:09 Liqiuyue9597

function shuffle(arr) {
  let len = arr.length;
  let index;
  while (len > 0) {
    index = Math.floor(Math.random() * len); 
    len--;
    [arr[len], arr[index]] = [arr[index], arr[len]];
  }
  return arr;
}

Liqiuyue9597 avatar Sep 28 '20 03:09 Liqiuyue9597