转自:http://www.cnblogs.com/a546558309/archive/2013/05/16/3081974.html

看了一段时间关于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菜鸟,如果有什么想法啥的,直接留言,相互交流一下

#1楼 2013-05-16 19:18 大家都不容易  
1
2
3
4
5
6
7
8
var arr = [{ name: 'aaa', grade: 30 }, { name: 'ccc', grade: 20 }, { name: 'bbb', grade: 40 }];
 
var ascArr = arr.sort(function(a, b) { return a.grade - b.grade });
 
var descArr = arr.sort(function(a, b) { return b.grade - a.grade });
 
console.log(ascArr);
console.log(descArr);
  
#2楼[楼主2013-05-17 10:20 香草柠檬  
@大家都不容易
你这个按数值排序可以,如果是字符的话就不行了




本文转载:CSDN博客