Javascript 數組排序詳解,javascript排序詳解

來源:互聯網
上載者:User

Javascript 數組排序詳解,javascript排序詳解

如果你接觸javascript有一段時間了,你肯定知道數組排序函數sort,sort是array原型中的一個方法,即array.prototype.sort(),sort(compareFunction),其中compareFunction是一個比較函數,下面我們看看來自Mozilla MDN 的一段描述:
If compareFunction is not supplied, elements are sorted by converting them to strings and comparing strings in lexicographic (“dictionary” or “telephone book,” not numerical) order. For example, “80″ comes before “9″ in lexicographic order, but in a numeric sort 9 comes before 80.

下面看些簡單的例子:

複製代碼 代碼如下:
// Output [1, 2, 3]
console.log([3, 2, 1].sort());

// Output ["a", "b", "c"]
console.log(["c", "b", "a"].sort());

// Output [1, 2, "a", "b"]
console.log(["b", 2, "a", 1].sort());


從上例可以看出,預設是按字典中字母的順序來排序的。

幸運的是,sort接受一個自訂的比較函數,如下例:

複製代碼 代碼如下:
function compareFunction(a, b) {
 if( a > b) {
  return -1;
 }else if(a < b) {
  return 1;
 }else {
  return 0;
 }
}
//Outputs ["zuojj", "Benjamin", "1"]
console.log(["Benjamin", "1", "zuojj"].sort(compareFunction));

排序完我們又有個疑問,如何控制升序和降序呢?

複製代碼 代碼如下:
function compareFunction(flag) {
 flag = flag ? flag : "asc";
 return function(a, b) {
  if( a > b) {
   return flag === "desc" ? -1 : 1;
  }else if(a < b) {
   return flag === "desc" ? 1 : -1;
  }else {
   return 0;
  }
 };
}
//Outputs ["1", "Benjamin", "zuojj"]
console.log(["Benjamin", "1", "zuojj"].sort(compareFunction()));
//Outputs ["zuojj", "Benjamin", "1"]
console.log(["Benjamin", "1", "zuojj"].sort(compareFunction("desc")));

comparFunction的定序是這樣的:
1.If it returns a negative number, a will be sorted to a lower index in the array.
2.If it returns a positive number, a will be sorted to a higher index.
3.And if it returns 0 no sorting is necessary.

下面我們來看看摘自Mozilla MDN上的一段話:
The behavior of the sort method changed between JavaScript 1.1 and JavaScript 1.2.為瞭解釋這段描述,我們來看個例子:

In JavaScript 1.1, on some platforms, the sort method does not work. This method works on all platforms for JavaScript 1.2.

In JavaScript 1.2, this method no longer converts undefined elements to null; instead it sorts them to the high end of the array.詳情請戳這裡。

複製代碼 代碼如下:
var arr = [];
arr[0] = "Ant";
arr[5] = "Zebra";
//Outputs ["Ant", 5: "Zebra"]
console.log(arr);
//Outputs 6
console.log(arr.length);
//Outputs "Ant*****Zebra"
console.log(arr.join("*"));
//排序
var sortArr = arr.sort();
//Outputs ["Ant", "Zebra"]
console.log(sortArr);
//Outputs 6
console.log(sortArr.length);
//Outputs "Ant*Zebra****"
console.log(sortArr.join("*"));

希望本文對你學習和瞭解sort()方法有協助,文中不妥之處還望批評斧正。

參考連結:https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Array/sort


javascript對數組的排序

arr.sort(sortNumber)
arr.sort():系統函數,處理arr數組相鄰兩個元素。
這裡sortNumber是自訂的排序條件。
因為sort()函數的排序條件是:參數大於0,arr的相鄰兩個元素交換位置;
參數小於0,arr的相鄰兩個元素不交換位置;
參數等於0,arr的相鄰兩個元素大小相等;所以sortNumber自訂函數必須返回一個數值。
(a-b)表示相鄰兩個元素按照前一個元素減去後一個元素.並返回這個數值,sort()函數根據這個數值的正負來確定arr當前兩個元素是否交換位置。
反之:b-a就變成倒序了。這就意味這b-a表示相鄰兩個元素按照後一個元素減去前一個元素.並返回這個數值,sort()函數根據這個數值的正負來確定arr當前兩個元素是否交換位置。
 
javascript 數組排序的問題

仔細讀懂你那段代碼上面的一段話 對你有協助

說明
如果調用該方法時沒有使用參數,將按字母順序對數組中的元素進行排序,說得更精確點,是按照字元編碼的順序進行排序。要實現這一點,首先應把數組的元素都轉換成字串(如有必要),以便進行比較。

如果想按照其他標準進行排序,就需要提供比較函數,該函數要比較兩個值,然後返回一個用於說明這兩個值的相對順序的數字。比較函數應該具有兩個參數 a 和 b,其傳回值如下:

若 a 小於 b,在排序後的數組中 a 應該出現在 b 之前,則返回一個小於 0 的值。
若 a 等於 b,則返回 0。
若 a 大於 b,則返回一個大於 0 的值。
參考資料:w3school
 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.