Riven952465

生活不止眼前的苟且,还有未来的苟且。

导航

对象数组排序函数

对象数组排序

  • 某些情况下我们创建的Array,会默认变成Object,
    var a = new Array();

    console.log(typeof a);
    // Object

所以我们需要一个函数来给对象数组进行排序。

    function compare(propertyName) {
        return function (object1, object2) {
            var value1 = object1[propertyName];
            var value2 = object2[propertyName];
            if (value2 > value1) {
                return -1;
            }
            else if (value2 < value1) {
                return 1;
            }
            else {
                return 0;
            }
        }
    }

使用:

    a.sort(compare('排序需要根据的属性名称', false));

posted on 2016-09-19 10:15  Riven952465  阅读(575)  评论(0编辑  收藏  举报