Skip to content

Latest commit

 

History

History
27 lines (21 loc) · 739 Bytes

shuffle.md

File metadata and controls

27 lines (21 loc) · 739 Bytes
标题 标签
shuffle(随机打乱数组) array,random,algorithm(数组,随机,算法)

随机化数组值的顺序,返回一个新数组。

const shuffle = ([...arr]) => {
  let m = arr.length;
  while (m) {
    const i = Math.floor(Math.random() * m--);
    [arr[m], arr[i]] = [arr[i], arr[m]];
  }
  return arr;
};

调用方式:

const foo = [1, 2, 3];
shuffle(foo); // [2, 3, 1], foo = [1, 2, 3]

应用场景