按属性排序

时间:2013-03-28 16:29:32

标签: javascript

我有这段代码

function Human(firstName,lastName,age)
{
    this.firstName = firstName;
    this.lastName =  lastName;
    this.age = age;
}

var firstHuman = new Human("Ivan","Ivanov",25);
var secondHuman = new Human("Petar","Petrov",34);
var thirdHuman = new Human("Ivailo", "Stoyanov",28);
var forthHuman = new Human("Petar", "Tudjarov",50);
var fifthHuman = new Human("Hari", "Qvorov",20);

var Humans = new Array (firstHuman,secondHuman,thirdHuman,forthHuman,fifthHuman);

我如何通过firstName对它们进行排序,使第五个人(H是字母表中最小的)成为数组中的第一个

1 个答案:

答案 0 :(得分:3)

Humans.sort(function(a, b){return a.firstName > b.firstName});

http://jsfiddle.net/3wyBc/