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数组排序 #31

Open
zhn4 opened this issue Mar 15, 2018 · 0 comments
Open

javascript数组排序 #31

zhn4 opened this issue Mar 15, 2018 · 0 comments

Comments

@zhn4
Copy link
Owner

zhn4 commented Mar 15, 2018

关于javascript数组排序
demo:http://jsbin.com/jahiquyaso/edit?js,console,output

var arr = [9, 3, 4, 54, 77, 79, 323, 1, 0]

var arr1 = arr.sort()

console.log(arr)// [0, 1, 3, 323, 4, 54, 77, 79, 9],首位数字排序

var arr2 = arr.sort(function(m, n) {
  if(m > n) {
    return 1
  }else if(m < n) {
    return -1
  }else {
    return 0
  }
})

console.log(arr2)// [0, 1, 3, 4, 9, 54, 77, 79, 323],正序

var arr3 = arr.sort(function(m, n) {
  if(m > n) {
    return -1
  }else if(m < n) {
    return 1
  }else {
    return 0
  }
})

console.log(arr3)// [323, 79, 77, 54, 9, 4, 3, 1, 0], 反序

新增随机排序
参考:https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Array/sort
demo:http://jsbin.com/puzoliluli/edit?js,console,output

// 随机排序
var arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

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

console.log(arr)

洗牌算法
参考:https://gaohaoyang.github.io/2016/10/16/shuffle-algorithm/#top

Array.prototype.shuffle = function() {
    var input = this;

    for (var i = input.length-1; i >=0; i--) {

        var randomIndex = Math.floor(Math.random()*(i+1));
        var itemAtIndex = input[randomIndex];

        input[randomIndex] = input[i];
        input[i] = itemAtIndex;
    }
    return input;
}
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