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

JavaScript 数组乱序 #44

Closed
PolluxLee opened this issue Jun 10, 2018 · 0 comments
Closed

JavaScript 数组乱序 #44

PolluxLee opened this issue Jun 10, 2018 · 0 comments

Comments

@PolluxLee
Copy link
Owner

PolluxLee commented Jun 10, 2018

1)

var values = [1, 2, 3, 4, 5];

values.sort(function(){
  return Math.random() - 0.5;
});

console.log(values);

2)

遍历数组元素,然后将当前元素与以后随机位置的元素进行交换

function shuffle(a) {
  for (let i = a.length; i; i--) {
    let j = Math.floor(Math.random() * i);
    [a[i - 1], a[j]] = [a[j], a[i - 1]];
  }
  return a;
}

References

mqyqingfeng/Blog#51

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

1 participant