扩展js对象数组的OrderByAsc和OrderByDesc方法

看了一段时间关于js原型的知识,js的扩展方法是基于原型的,如Array.prototype.XXXX就是给Array扩展XXX方法,然后数组都能使用这个方法了。

在对象数组里面经常有根据属性来进行排序的,升序,降序的,于是自己就想写一个类似于C#里面的orderBy的方法,代码如下:

       Array.prototype.OrderByAsc = function (func) {
            var m = {};
            for (var i = 0; i < this.length; i++) {
                for (var k = 0; k < this.length; k++) {
                    if (func(this[i]) < func(this[k])) {
                        m = this[k];
                        this[k] = this[i];
                        this[i] = m;
                    }
                }
            }
            return this;
        }

        Array.prototype.OrderByDesc = function (func) {
            var m = {};
            for (var i = 0; i < this.length; i++) {
                for (var k = 0; k < this.length; k++) {
                    if (func(this[i]) > func(this[k])) {
                        m = this[k];
                        this[k] = this[i];
                        this[i] = m;
                    }
                }
            }
            return this;
        }

 

调用的方法如下:

  var arr = [{ name: 'aaa', grade: 20 }, { name: 'ccc', grade: 30 }, { name: 'bbb', grade: 40 }];

        var orderArr = arr.OrderByDesc(function (a) {
            return a.grade;
        });

 

 

然后输出一下,看一下结果吧:

    for (var i = 0; i < orderArr.length; i++) {
            document.write(orderArr[i].name);
        }

本人js菜鸟,如果有什么想法啥的,直接留言,相互交流一下

posted @ 2013-05-16 15:41  kevinzw  阅读(5214)  评论(2编辑  收藏  举报