Javascript排序问题

1)一个简单的排序:对于一般的数组可以直接使用sort,默认是升序;

  

var values = [1, 3, 2, 4, 5];
values.sort();

2)sort本身可以接受一个参数,是一个函数对象的引用,来实现自定义的排序;

function compare(value1, value2) {
    if(value1 < value2) {
        return -1;
    }
    if(value1 > value2) {
        return 1;
    } else {
        return 0;
    }
}

var values= [1, 3, 2, 4, 5]; 
values.sort(compare);

3)为了实现指明按照对象的属性来排序,我们可以定义一个函数,这个函数接收一个属性,返回一个函数,并将这个函数作为sort的参数来实现

function createComparisonFunction(propertyName) {
    return function(object1, object2) {
        var value1 = object1[propertyName];
        var value2 = object2[propertyName];

        if(value1 < value2) {
            return -1;
        }
        if(value1 > value2) {
            return 1;
        } else {
            return 0;
        }
    };
}


var data = [{name: "zachary", age:28}, {name: "Kin", age: 21}];
data.sort(createComparisonFunction("age"));

同时上述的方法可以针对于我们自定义的对象(类),如下:

function createComparisonFunction(propertyName) {
    return function(object1, object2) {
        var value1 = object1[propertyName];
        var value2 = object2[propertyName];

        if(value1 < value2) {
            return -1;
        }
        if(value1 > value2) {
            return 1;
        } else {
            return 0;
        }
    };
}

function Person(name, age) {
    this.name = name;
    this.age= age;
    this.friends = ["Shelby", "Court"];
}
//@overwirte the prototype
Person.prototype = {
    constructor : Person,
    sayName : function() {
        console.log(this.name);
    }
};

var Person1 = new Person("Nicholas", 29);
var Person2 = new Person("Kin", 21);
var Person3 = new Person("Mike", 30);

var Personset = [Person1, Person2, Person3];
Personset.sort(createComparisonFunction("age"));

 

posted @ 2015-09-27 16:39  Kinthon  阅读(250)  评论(0编辑  收藏  举报