js中數組Array對象的方法sort()的應用


一、 sort()方法的介紹  

 //給一組數據排序
    var arrNum = [12,1,9,23,56,100,88,66];
    console.log("排序前的數組:"+arrNum);
    arrNum.sort();//默認按照字母排序
    console.log("排序后的數組:"+arrNum);

    //對數組進行升序排列,將函數作為參數傳入
    arrNum.sort(function (a,b) {
        return a-b;//數組中兩兩比較,結果為正(a>b),則互換位置,小的在前面(從索引0開始,分別和后面元素比較)
    });
    console.log("升序排序后的數組:"+arrNum);

    //對數組進行降序排列,將函數作為參數傳入
    arrNum.sort(function (a,b) {
        return b-a;//數組中兩兩比較,結果為正,則互換位置,大的在前面
    });
    console.log("降序排序后的數組:"+arrNum);


二、 sort()方法的高級應用(按照對象數組中對象的屬性進行排序)
  function Student(name,age,score) {
        this.name = name;
        this.age = age;
        this.score = score;
    }

    var stu1 = new Student("寒殤凌雪",23,100);
    var stu2 = new Student("花木扶疏",25,97);
    var stu3 = new Student("北城以北",20,95);
    var stu4 = new Student("南柯一夢",24,99);
    var stu5 = new Student("水墨淡彩",22,95);

    var arr = [];
    arr.push(stu1,stu2,stu3,stu4,stu5);
    console.log("排序前輸出每一個索引對應的值如下:")
    for(i in arr){
        console.log(arr[i]);
    }

    // arr.sort(upSort("score"));
    arr.sort(upSort("score","age"));
    console.log("升序排列后輸出每一個索引對應的值如下:")
    for(i in arr){
        console.log(arr[i]);
    }

    //arr.sort(lowSort("score"));
    arr.sort(lowSort("score","age"));
    console.log("降序排列后輸出每一個索引對應的值如下:")
    for(i in arr){
        console.log(arr[i]);
    }


/*    //升序排列
    function upSort(property) {//指定某個屬性的排序
        return function (a,b) {
            return a[property] - b[property];
        }
    }*/


    function upSort(score,age) {//指定某個屬性的排序
        return function (a,b) {
            if(a.score == b.score){//當分數相等,按照年齡排序
                return a.age - b.age;
            }
            return a.score - b.score;
        }
    }


    //降序排列
/*    function lowSort(property) {//指定某個屬性的排序
        return function (a,b) {
            return b[property] - a[property];
        }
    }*/

     function lowSort(score,age) {//指定某個屬性的排序
         return function (a,b) {
             if(a.score == b.score){//當分數相等,按照年齡排序
                 return b.age - a.age;
             }
             return b.score - a.score;
         }
        }



    /*var arr1 = [12,8,45,10];
    arr1.sort(function (a,b) {
        return a-b;//升序
    });
    console.log(arr1);

    arr1.sort(function (b,a) {
        return a-b;//升序
    });
    console.log(arr1)*/

 


 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM