js笔记--高阶函数sort()

sort()的默认排序为 先将元素转化为字符串,然后按照ASCII的大小比较进行排序,所以直接对数字排序会出错。

(1)要按数字大小排序,应写为:

  var arr=[10,20,1,2];

  arr.sort(function (x, y) {
    if (x < y) {
      return -1;
    }
    if (x > y) {
      return 1;
    }
    return 0;
  });
  console.log(arr); // [1, 2, 10, 20]

  倒序排序:

  arr.sort(function (x, y) {
      if (x < y) {
          return 1;
      }
      if (x > y) {
          return -1;
      }
      return 0;
  }); // [20, 10, 2, 1]
(2)忽略字符串大小写(即统一转化为大写或小写),对字符串进行排序:
  var arr = ['Google', 'apple', 'Microsoft'];
  arr.sort(function (s1, s2) {
      x1 = s1.toUpperCase();
      x2 = s2.toUpperCase();
      if (x1 < x2) {
          return -1;
      }
      if (x1 > x2) {
          return 1;
      }
      return 0;
  }); // ['apple', 'Google', 'Microsoft']

!!!sort()方法直接改变的是当前数组,不是产生新的数组!
 

 参考廖雪峰老师的官方网站

原文地址:https://www.cnblogs.com/lst-315/p/11468493.html