# js:数组自定义排序

reverse()方法用于反转数组。

var values = [0 ,1 , 5, 10 ,15];
values.sort();

console.log(values); // 0,1,10,15,5

sort()方法可以接受一个比较函数作为参数，以便我们指定哪个值位于哪个值的前面


var stu1 = {
name: "python", age: 80, grade: 99,
toString: function () {
return this.name + " , " + this.age + " , " + this.grade;
}
};
var stu2 = {
name: "javascript", age: 30, grade: 88, toString: function () {
return this.name + " , " + this.age + " , " + this.grade;
}
};
var stu3 = {
name: "php", age: 18, grade: 59, toString: function () {
return this.name + " , " + this.age + " , " + this.grade;
}
};
var stu4 = {
name: "vb", age: 50, grade: 70, toString: function () {
return this.name + " , " + this.age + " , " + this.grade;
}
};
var stu5 = {
name: "shell", age: 60, grade: 70, toString: function () {
return this.name + " , " + this.age + " , " + this.grade;
}
};
var stu6 = {
name: "java", age: 40, grade: 99, toString: function () {
return this.name + " , " + this.age + " , " + this.grade;
}
};

var langArr = [stu1, stu2, stu3, stu4, stu5, stu6];

console.log("排序前：" + langArr);
console.log("-------------------");

function compare(a, b) {
return -5;
return 0;
} else {
return 5;
}
} // todo:简单排序，仅仅通过分数进行排序

function cmp(a, b) {

return -5;
// return 0;
if (a.age < b.age) {
return -4;
} else if (a.age === b.age) {
return a.name.localeCompare(b.name);
} else {
return 4;
}
} else {
return 5;
}
} // todo:复杂排序，先比较分数，然后是年龄，最后是名字字符串

// langArr.sort(compare);
langArr.sort(cmp);

console.log("排序后：" + langArr);


排序前：python , 80 , 99,javascript , 30 , 88,php , 18 , 59,vb , 50 , 70,shell , 60 , 70,java , 40 , 99
-------------------