一、sort()方法:
- 调用每个数组项的toString()方法
- 比较字符串,按升序排列数组
var items = ["d", "a", "b", "e", "c"];
items.sort();
alert(items);
alert()会先调用数组的toString方法然后显示
二、数组的值是number的情况下调用sort()方法
sort()不会按照数值大小升序排列而是按字符串大小排列
var items = [8, 10, 3, 11, 2, 1];
items.sort();
alert(items);
三、如何按数值大小排序?
答案:sort()方法可以接受一个参数,该参数只能是函数,我们成这个函数为比较函数
比较函数需要至少接受2个参数指定排序规则,其返回值如下:
若 a 小于 b,在排序后的数组中 a 应该出现在 b 之前,则返回一个小于 0 的值。
若 a 等于 b,则返回 0。
若 a 小于 b,在排序后的数组中 a 应该出现在 b 之前,则返回一个小于 0 的值。
var items = [8, 10, 3, 11, 2, 1];
function compare(num1, num2) {
if (num1 > num2) {
return 1;
} else if (num1 == num2) {
return 0;
} else {
return -1
};
}
items.sort(compare);
alert(items);
四、改进(三、)中的比较函数
var items = [8, 10, 3, 11, 2, 1];
function compare(num1, num2) {
return num1 - num2;
}
items.sort(compare);
alert(items);
五、依据对象的属性1的顺序,排列对象的属性2
var person1 = {
name: "姚明",
age: 38,
height: 224,
toString: function() {
return this.name;
}
};
var person2 = {
name: "郭敬明",
age: 27,
height: 140,
toString: function() {
return this.name;
}
};
var person3 = {
name: "老刘",
age: 40,
height: 175,
toString: function() {
return this.name;
}
}
persons = [person1, person2, person3];
function compare(property) {
return function(a, b) {
aProperty = a[property];
bProperty = b[property];
return aProperty - bProperty;
}
}
persons.sort(compare("height"));
alert(persons);
六、在(五、)的基础上,实现选择升序降序功能
var person1 = {
name: "姚明",
age: 38,
height: 224,
toString: function() {
return this.name;
}
};
var person2 = {
name: "郭敬明",
age: 27,
height: 140,
toString: function() {
return this.name;
}
};
var person3 = {
name: "老刘",
age: 40,
height: 175,
toString: function() {
return this.name;
}
}
persons = [person1, person2, person3];
function compare(property, rev) {
if (rev == undefined) {
rev = 1;
} else {
rev = (rev) ? 1 : -1;
}
return function(a, b) {
aProperty = a[property];
bProperty = b[property];
return rev * (aProperty - bProperty);
}
}
persons.sort(compare("height", false));
alert(persons);