首页 > 编程语言 > 详细

Javascript排序问题

时间:2015-09-27 17:24:48      阅读:258      评论:0      收藏:0      [点我收藏+]

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"));

 

Javascript排序问题

原文:http://www.cnblogs.com/kinthon/p/4842394.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!