返回修改后数组方法

push,unshift  pop,shift,  reverse   splice  sort  //返回修改后数组

sort - > 按照ascii码来排序的,

1. 参数a, b

2.返回值: 1、负值, a就排前面

     2、正值, b就排前面

               3、0 保持不动

var arr = [8, 3, 4, 5, -5];   //冒泡排序法
arr.sort(function(a, b){
    // return a - b;  
    //
    if(a > b){
        return 1
    }else{
        return -1
    }
})

 随机排序


var arr = [8, 3, 4, 5, -5];
arr.sort(function(a, b){
// var rand = Math.random();
// if(rand - 0.5 > 0){
// return 1
// }else{
// return -1
// }

//或
return Math.random() - 0.5
})
console.log(arr)
 

根据字符串长度排序

var arr = ['123', '1457', '12875', '1', '165', '12', '136', '19'];
arr.sort(function(a, b){
    return a.length - b.length
})
console.log(arr)

 按照字节数排序

var arr = ['你好', 'World', 'Hello', '大家好', '吃饭'];
arr.sort(function(a, b){
    return codeat(a) - codeat(b)
})
console.log(arr)
function codeat(str){
    var tt = str.length;
    for(var i = 0; i < str.length; i++){
        if(str.charCodeAt(i) > 255){
            tt++
        }
    }
    return tt
}

 

posted @ 2019-02-08 19:36  阿|明  阅读(422)  评论(0编辑  收藏  举报