Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
wingmeng opened this issue Sep 28, 2019 · 0 comments
Open

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

wingmeng opened this issue Sep 28, 2019 · 0 comments

Comments

@wingmeng
Copy link
Collaborator

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

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();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant