JavaScript中用sort方法進行二維數組排序 — 第5.2.5節__Java

來源:互聯網
上載者:User
JavaScript中數組排序方法

用到的最多的當然是封裝好的sort()方法了
一:sort()方法怎麼使用。
sort方法並不像我們想的那麼容易使用,不是單純的arr.sort()就行了,需要我們定義裡面的回呼函數。因為sort()方法預設情況下按照升序排列數組項,sort()方法會調用toString()轉型方法,然後比較得到的字串,即使我們比較的是數字,他也會把數字轉為字串以後再排序
請看下面例子:

var arr1 = [0, 1, 3, 10, 16, 5, 9, 0, 3];var arr2 = ['bangbang', 'father', 'mother', 'brother', 'sister', true, false, 0, 1, 6, 13];console.log(arr1.sort()) //很明顯,這樣不是我們要的結果,[ 0, 0, 1, 10, 16, 3, 3, 5, 9 ]console.log(arr2.sort()); //[ 0,1,13,6,'bangbang','brother',false,'father','mother','sister',true]//傳入自訂回呼函數之後function ascend(a,b){    return a-b;}//降序排列function descend(a,b){    return b-a;}console.log(arr1.sort(ascend));     //[ 0, 0, 1, 10, 16, 3, 3, 5, 9 ]console.log(arr1.sort(descend));    //[ 16, 10, 9, 5, 3, 3, 1, 0, 0 ]

二:用sort方法進行二維數組的排序。

var arr1 = [[4,5,7],[11,3,6,100,77],[12,9,12,10],[3,1,2,99,22]];function ascend(x,y){    return x[3] - y[3];  //按照數組的第4個值升序排列}function descend(x,y){    return y[0] - x[0];  //按照數組的第1個值升序排列}console.log(arr1.sort(ascend));console.log(arr1.sort(descend));

當然還有其他的排序方法,再次我只說封裝好的,其實排序有很多種,關鍵看你怎麼使用。
三:順便什麼是reverse()方法。怎麼使用。
reverse方法會反轉數組項的順序,請看如下樣本:

var arr1 = [0, 1, 3, 10, 16, 5, 9, 0, 3];var arr2 = ['bangbang', 'father', 'mother', 'brother', 'sister', true, false, 0, 1, 6, 13];console.log(arr1.reverse());//[ 3, 0, 9, 5, 16, 10, 3, 1, 0 ]console.log(arr2.reverse());//[ 13,6,1,0,false,true,'sister','brother','mother','father','bangbang' ]

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.