fezaoduke / fe-practice-hard

晚练课
69 stars 6 forks source link

第 118 期(算法-排序):数组乱序 #121

Open wingmeng opened 5 years ago

wingmeng commented 5 years ago

随机打乱一个数组中项目的顺序:

function shuffle(arr) {
  arr = [...arr];

  for (let i = 0, len = arr.length; i < len; i++) {
    var rdmIndex = i + Math.floor(Math.random() * (len - i));
    [arr[i], arr[rdmIndex]] = [arr[rdmIndex], arr[i]];
  }

  return arr;
}

shuffle([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]);

或者封装到数组原型链上:

Array.prototype.shuffle = function() {
  arr = [...this];

  for (let i = 0, len = arr.length; i < len; i++) {
    var rdmIndex = i + Math.floor(Math.random() * (len - i));
    [arr[i], arr[rdmIndex]] = [arr[rdmIndex], arr[i]];
  }

  return arr;
}

[1, 2, 3, 4, 5, 6, 7, 8, 9, 10].shuffle();