sort()方法的应用

Posted hzsll

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了sort()方法的应用相关的知识,希望对你有一定的参考价值。

 

引用:函数作为参数

var fn_by = function(id) {
    return function(o, p) {
        var a, b;
        if (typeof o === "object" && typeof p === "object" && o && p) {
            a = o[id];
            b = p[id];
            if (a === b) {
                return 0;
            }
            if (typeof a === typeof b) {
                return a > b ? -1 : 1; //降序使用 “>”, 升序使用“<”
            }
            return typeof a > typeof b ? -1 : 1; //降序使用“>”, 升序使用“<”
        } else {
            throw ("error");
        }
    }
};
arrayObj.sort(fn_by("id"));

 

以上是关于sort()方法的应用的主要内容,如果未能解决你的问题,请参考以下文章