美文网首页js
数组随机排序

数组随机排序

作者: u14e | 来源:发表于2017-02-24 12:15 被阅读4次
var arr = [1,2,3,4,5,6,7,8,9,10]; 
function randomSort1(arr) {
    for (let i = 0, len = arr.length; i < len; i++) {
        let j = Math.floor(Math.random() * len);
        [ arr[i], arr[j] ] = [ arr[j], arr[i] ];
    }
    return arr;
}
console.log(randomSort1(arr))
let arr = [1,2,3,4,5,6,7,8,9,10]; 
function randomSort2(arr) {
    let randomArr = [];
    while (arr.length > 0) {
        let num = Math.floor(Math.random() * arr.length);
        randomArr.push(arr[num]);
        arr.splice(num, 1);
    }
    return randomArr;
}
console.log(randomSort2(arr))
let arr = [1,2,3,4,5,6,7,8,9,10];
arr.sort(function(){
    return Math.random() - 0.5;
})
console.log(arr);

相关文章

网友评论

    本文标题:数组随机排序

    本文链接:https://www.haomeiwen.com/subject/nfcwwttx.html