zoukankan      html  css  js  c++  java
  • Js 数组对象排序

    1.定义函数

     /**
         * 数组对象排序函数
         * @param {any} name 排序字段
         * @param {any} order 升、降(这里事true、false记得处理下)
         */
        var by = function (name,order) {
            return function (o, p) {
                var a, b;
                if (typeof o === "object" && typeof p === "object" && o && p) {
                    a = o[name];
                    b = p[name];
                    if (a === b) {
                        return 0;
                    }
                    if (typeof a === typeof b) {
                        if (order) {
                            return a < b ? -1 : 1;
                        }
                        return a > b ? -1 : 1;
                    }
                    if (order) {
                        return typeof a < typeof b ? -1 : 1;
                    }
                    return typeof a > typeof b ? -1 : 1;
                   
                }
                else {
                    throw ("error");
                }
            }
        }

    2.使用方式

    //数组
    var employees=[]
    employees[0]={name:"George", age:32, retiredate:"March 12, 2014"}
    employees[1]={name:"Edward", age:17, retiredate:"June 2, 2023"}
    employees[2]={name:"Christine", age:58, retiredate:"December 20, 2036"}
    employees[3]={name:"Sarah", age:62, retiredate:"April 30, 2020"}
    //调用
    employees.sort(by("age"),true);




  • 相关阅读:
    java中文件的读取和写入
    ==与equal在java中应用的感悟
    Gson心得小笔记
    几种排序的算法
    HttpClient的使用方法
    StringBuffer
    laravel5.5容器
    常用会话管理方式
    css一些事儿
    关于时间的梳理
  • 原文地址:https://www.cnblogs.com/lbonet/p/7880249.html
Copyright © 2011-2022 走看看