技術(shù)頻道導航
HTML/CSS
.NET技術(shù)
IIS技術(shù)
PHP技術(shù)
Js/JQuery
Photoshop
Fireworks
服務器技術(shù)
操作系統(tǒng)
網(wǎng)站運營

贊助商

分類目錄

贊助商

最新文章

搜索

js使用sort()函數(shù)對二維數(shù)組快速排序的寫法

作者:admin    時間:2015-7-3 9:31:4    瀏覽:

js數(shù)組的排序方法有很多,冒泡法,插入法等等,不過對于數(shù)組的排序來說,js提供了一個非常實用的函數(shù)sort(),可以對數(shù)組進行自動排序,不需要我們手寫函數(shù)代碼進行排序。然而,當我需要排序的數(shù)據(jù)是一些二維數(shù)組時,sort()方法就不能再直接使用了,需要使用一點技巧。本文介紹如何使用js對二維數(shù)組進行快速排序的寫法。

假如我們有幾組二維數(shù)組(姓名,年齡):

'jack',20
'tony',25
'stone',26
'mandy',23

現(xiàn)在需要對他們按照年齡從小到大來排序,我們該怎樣編寫代碼呢?

1)、自定義對象屬性:

function Persion(name,age){
            this.name=name;
            this.age=age;
}

2)、聲明數(shù)組,并賦值

var objectList = new Array();
objectList.push(new Persion('jack',20));
objectList.push(new Persion('tony',25));
objectList.push(new Persion('stone',26));
objectList.push(new Persion('mandy',23));

3)、按年齡從小到大排序

objectList.sort(function(a,b){
return a.age-b.age});

4)、輸出數(shù)組數(shù)據(jù)

for(var i=0;i<objectList.length;i++){
            document.writeln('<br />age:'+objectList[i].age+' name:'+objectList[i].name);
}

輸出結(jié)果為:

age:20 name:jack
age:23 name:mandy
age:25 name:tony
age:26 name:stone

 完整代碼如下:

<script type="text/javascript">
        var objectList = new Array();
        function Persion(name,age){
            this.name=name;
            this.age=age;
        }
        objectList.push(new Persion('jack',20));
        objectList.push(new Persion('tony',25));
        objectList.push(new Persion('stone',26));
        objectList.push(new Persion('mandy',23));
        //按年齡從小到大排序
        objectList.sort(function(a,b){
            return a.age-b.age});
        for(var i=0;i<objectList.length;i++){
            document.writeln('<br />age:'+objectList[i].age+' name:'+objectList[i].name);
        }
</script>

可能遇到的問題

“10,51,100,50”排序為什么是“10,100,50,51”?

默認情況下sort方法是按ascii字母順序排序的,而非我們認為是按數(shù)字大小排序。

如何處理?參考如下例子:

var arrDemo = new Array();
arrDemo[0] = 10;
arrDemo[1] = 50;
arrDemo[2] = 51;
arrDemo[3] = 100;
arrDemo.sort(); //調(diào)用sort方法后,數(shù)組本身會被改變,即影響原數(shù)組
alert(arrDemo);//10,100,50,51 默認情況下sort方法是按ascii字母順序排序的,而非我們認為是按數(shù)字大小排序
arrDemo.sort(function(a,b){return a>b?1:-1});//從小到大排序
alert(arrDemo);//10,50,51,100
arrDemo.sort(function(a,b){return a<b?1:-1});//從大到小排序
alert(arrDemo);//100,51,50,10

我要數(shù)組從大到小排序怎么寫?

<script type="text/javascript">
        var arrSimple2=new Array(1,8,7,6);
        arrSimple2.sort(function(a,b){
            return b-a});
        document.writeln(arrSimple2.join());
        //解釋:a,b表示數(shù)組中的任意兩個元素,若return > 0 b前a后;reutrn < 0 a前b后;a=b時存在瀏覽器兼容
        //簡化一下:a-b輸出從小到大排序,b-a輸出從大到小排序。
</script>

通過上述幾個實例的學習,js對數(shù)組(包括二維數(shù)組)的排序就沒有問題了。

標簽: 排序  
相關(guān)文章
    x
    • 站長推薦
    /* 左側(cè)顯示文章內(nèi)容目錄 */