数组的排序sort

2020-03-24  本文已影响0人  杨戬Yj

sort() 方法用于对数组的元素进行排序。

它会直接修改当前Array的元素位置,直接调用时,按照默认升序排序,默认排序顺序是根据字符串ASSIC码

arrayObject.sort(sortby);
// 参数sortby  可选,用来规定排序的顺序,但必须是函数
var arr = [3,9,4,7,8,1,5,3];
var sort = arr.sort();
console.log(sort); // [1, 3, 3, 4, 5, 7, 8, 9]
var arr = [1, 3, 9, 'A', 'X', 'G', 'c', 6];
var sort = arr.sort();
console.log(sort); 
console.log(arr); 
 // 返回值sort即为arr 的值  [1, 3, 6, 9, "A", "G", "X", "c"]   
var arr = ['123', '321', '1000', '50'];
console.info(arr.sort()); //["1000", "123", "321", "50"]  默认按照ASSIC码排列(升序)
console.info(typeof(arr[0])); //string 
function upNum(a,b){
    return a-b;  //升序排列
}
function downNum(a,b){
    return b-a;  //降序排序
}
var numarr=[30, 995, 34, 10, 100, 98, 321, 123];

console.log(numarr.sort(downNum));// [995, 321, 123, 100, 98, 34, 30, 10]
console.log(numarr.sort(upNum)); // [10, 30, 34, 98, 100, 123, 321, 995]
var arr1=[{name:'菲菲',age:18}, {name:'关关',age:26}, {name:'伊人',age:16}];
function compare(prop){
    return function(a,b){
        var val1 = a[prop];  //此处不能用a.prop,b.prop
        var val2 = b[prop];
        return val1 - val2;
    }
}
console.log(arr1.sort(compare('age')));
/*
    0: {name: "伊人", age: 16}
    1: {name: "菲菲", age: 18}
    2: {name: "关关", age: 26}
*/
function sortBy(prop, rev){
    rev = (rev) && rev > 0 ? 1 : -1;
    console.log(rev); 
    return function(a, b){
        var a = a[prop];  //此处不能用a.prop,b.prop
        var b = b[prop]; 
        if(rev > 0){
            return a - b;  //升序
        }
        if(rev < 0){
            return b - a;  //降序
        }
        return 0;
    }
}
console.info(arr1.sort(sortBy('age'))); //无参数,参数小于等于0 降序,参数大于0 升序
/*  默认降序
    0: {name: "关关", age: 26}
    1: {name: "菲菲", age: 18}
    2: {name: "伊人", age: 16}
*/
上一篇下一篇

猜你喜欢

热点阅读