zoukankan      html  css  js  c++  java
  • 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()方法直接改变的是当前数组,不是产生新的数组!
     

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

  • 相关阅读:
    HTML head 头标签
    p标签text-align:justify以及CSS文字两端对齐
    css雪碧图制作
    ps去掉图片上的文字
    Qt Quick之TableView的使用
    Qt Quick之Canvas
    Qt Quick中的信号与槽
    QT之在QML中使用C++类和对象
    rhel7+apache+c cgi+动态域名实现web访问
    (转载)JDOM/XPATH编程指南
  • 原文地址:https://www.cnblogs.com/lst-315/p/11468493.html
Copyright © 2011-2022 走看看