国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > JavaScript > 正文

Javascript 數(shù)組排序詳解

2019-11-20 14:00:19
字體:
來源:轉載
供稿:網(wǎng)友

如果你接觸javascript有一段時間了,你肯定知道數(shù)組排序函數(shù)sort,sort是array原型中的一個方法,即array.prototype.sort(),sort(compareFunction),其中compareFunction是一個比較函數(shù),下面我們看看來自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接受一個自定義的比較函數(shù),如下例:

復制代碼 代碼如下:

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的排序規(guī)則是這樣的:
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

發(fā)表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發(fā)表
主站蜘蛛池模板: 海林市| 英吉沙县| 麦盖提县| 沐川县| 阿拉善右旗| 桦川县| 新余市| 新宁县| 云霄县| 成武县| 恭城| 陆良县| 郁南县| 临江市| 高清| 馆陶县| 乐安县| 西乌珠穆沁旗| 临夏县| 白朗县| 土默特左旗| 扶风县| 长寿区| 赤壁市| 屯留县| 和硕县| 章丘市| 陇西县| 商丘市| 上栗县| 松桃| 保德县| 卢氏县| 南开区| 安平县| 库伦旗| 上思县| 马关县| 遂川县| 德昌县| 合肥市|