zoukankan      html  css  js  c++  java
  • JavaScript深入理解sort()方法

    一. 基本用法

    let arr1 = [3, 5, 7, 1, 8, 7, 10, 20, 19]
    console.log(arr1.sort())
    // [1, 10, 19, 20, 3, 5, 7, 7, 8]
    

    如果调用该方法时没有使用参数,将按字母顺序对数组中的元素进行排序,说得更精确点,是按照字符编码的顺序进行排序。要实现这一点,首先应把数组的元素都转换成字符串(如有必要),以便进行比较。

    其实,在使用sort()进行排序的时候会调用toString()函数将其值转换成字符串在进行比较,是按ASCII进行比较的。

    于是,在比较数字时会转换成字符串再比较,结果就会不准确。

    二. 改进用法

    let arr1 = [3, 5, 7, 1, 8, 7, 10, 20, 19]
    console.log(arr1.sort(function (a, b) {
        if (a < b) {
            return -1
        }
        if (a > b) {
            return 1
        }
        return 0
    }))
    // [1, 3, 5, 7, 7, 8, 10, 19, 20]
    console.log(arr1.sort(function (a, b) {
        return a - b
    }))
    // [1, 3, 5, 7, 7, 8, 10, 19, 20]
    

    sort()同时也是一个高阶函数,里面可以放一个比较函数:arr.sort(compareFunction)

    arr.sort(function (a, b) {
        return ?
    })
    
    • 若compareFunction返回值小于0,a排在b前面,即a与b的位置不变。
    • 若compareFunction返回值等于0,a与b的位置不变。
    • 若compareFunction返回值大于0,a排在b的后面,即a与b的位置交换。

    即若返回值大于0的时候交换a与b的位置,其他情况位置不变。

    • 升序:return a - b
    • 降序:return b - a
    // 降序示例
    let arr1 = [3, 5, 7, 1, 8, 7, 10, 20, 19]
    console.log(arr1.sort(function (a, b) {
        return b - a
    }))
    // [20, 19, 10, 8, 7, 7, 5, 3, 1]
    console.log(arr1.sort((a, b) => {
        return b - a
    }))
    // [20, 19, 10, 8, 7, 7, 5, 3, 1]
    

    三. 比较数组中的对象

    let arr2 = [
        {
            name: 'mazey0',
            value: 3
        },
        {
            name: 'mazey1',
            value: 5
        },
        {
            name: 'mazey2',
            value: 7
        },
        {
            name: 'mazey3',
            value: 1
        },
        {
            name: 'mazey4',
            value: 10
        },
        {
            name: 'mazey5',
            value: 7
        }
    ]
    // 升序
    let arr3 = arr2.sort((a, b) => {
        return a.value - b.value
    })
    arr3.forEach((value, index, arr) => {
        console.log(value.value)
    })
    // 1 3 5 7 7 10
    

    JavaScript深入理解sort()方法

  • 相关阅读:
    linux eclipse cdt make error 127
    centos 安装网络错误
    c++ string 结束符‘00’
    北京市工资交税情况
    gprof参数说明及常见错误
    【转】Eclipse Plugin 在 Console上打印出message
    C++做client Java做客户端传送数据
    word统计章节字数
    【转】Profiling application LLC cache misses under Linux using Perf Events
    【转】eclipse插件开发,调试运行,导出与安装
  • 原文地址:https://www.cnblogs.com/mazey/p/7881984.html
Copyright © 2011-2022 走看看