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()方法直接改变的是当前数组,不是产生新的数组!
     

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

  • 相关阅读:
    移除roadhog用webpack4代替
    git pull request
    java 希尔排序 归并排序 快速排序 三路快速排序
    简洁的 async await
    react-navigation 实现简单登录 跳转路由
    d3序数比例尺理解
    echarts vue 甘特图实现
    element table 实现鼠标拖拽选中
    CSS一些总结
    Nginx location 匹配规则
  • 原文地址:https://www.cnblogs.com/lst-315/p/11468493.html
Copyright © 2011-2022 走看看