sort()的默认排序为 先将元素转化为字符串,而后按照ASCII的大小比较进行排序,因此直接对数字排序会出错。javascript
(1)要按数字大小排序,应写为:java
var arr=[10,20,1,2];数组
arr.sort(function (x, y) {
if (x < y) {
return -1;
}
if (x > y) {
return 1;
}
return 0;
});
console.log(arr); // [1, 2, 10, 20]app
倒序排序:网站
arr.sort(function (x, y) { if (x < y) { return 1; } if (x > y) { return -1; } return 0; }); // [20, 10, 2, 1]
(2)忽略字符串大小写(即统一转化为大写或小写),对字符串进行排序:
var arr = ['Google', 'apple', 'Microsoft']; arr.sort(function (s1, s2) { x1 = s1.toUpperCase(); x2 = s2.toUpperCase(); if (x1 < x2) { return -1; } if (x1 > x2) { return 1; } return 0; }); // ['apple', 'Google', 'Microsoft']
!!!sort()方法直接改变的是当前数组,不是产生新的数组!
参考廖雪峰老师的官方网站spa