最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

Javascript 數組排序詳解

 更新時間:2014年10月22日 10:35:13   投稿:hebedich  
JavaScript實現(xiàn)多維數組、對象數組排序,其實用的就是原生的sort()方法,用于對數組的元素進行排序。今天我們就來詳細探討下sort()方法

如果你接觸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的排序規(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

相關文章

最新評論

新和县| 庄河市| 临泽县| 措勤县| 台安县| 白山市| 石河子市| 龙游县| 开化县| 孝义市| 固原市| 南丰县| 简阳市| 九江县| 玉龙| 永城市| 平舆县| 桓仁| 芒康县| 莒南县| 胶州市| 丰台区| 安宁市| 河池市| 琼结县| 堆龙德庆县| 白河县| 黎城县| 武安市| 抚顺市| 贵溪市| 淮北市| 广元市| 三明市| 湖口县| 宁河县| 东光县| 册亨县| 洪泽县| 大新县| 琼海市|