Skip to content

打乱数组的两种方法【最快vs最慢】 #4

@Veveue

Description

@Veveue
//fast
function shuffle(arr) {
    var i, temp, j, len = arr.length;
    for (i = 0; i < len; i++) {
        j = ~~ (Math.random() * len);
        temp = arr[i];
        arr[i] = arr[j];
        arr[j] = temp;
    }
    return arr;
}

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

性能测试

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions