js数组排序
数组排序函数
reverse()
反转原数组顺序sort()
将数组所有元素按字符串进行排序
let arr = [1, 25, 6, 33, 22, [4, 9]]
console.log(arr.reverse()); // [ [ 4, 9 ], 22, 33, 6, 25, 1 ]
// 实际上sort默认是将数组所有元素转换为字符串,作为映射进行排序
// 实际排序的是['1', '25', '6', '33',' 22', '4, 9']
console.log(arr.sort()); // [ 1, 22, 25, 33, [ 4, 9 ], 6 ]
自定义排序
sort()可接收一个比较函数作为参数
比较函数有两个参数a和b,这两个参数是数组的两个元素
比较函数返回一个数字n
- 如果n>0,则a在b后面
- 如果n<0,则a在b前面
- 否则ab部分先后
let arr = [1, 25, 6, 33, 22]
console.log(arr.sort((a, b) => a - b)) // [ 1, 6, 22, 25, 33 ]
console.log(arr.sort((a, b) => b - a)) // [ 33, 25, 22, 6, 1 ]
示例:根据年龄将person数组排序
class Person {
constructor(name, age) {
this.name = name
this.age = age
}
}
let persons = [
new Person('T', 23),
new Person('Y', 32),
new Person('N', 20)
]
console.log(persons.sort((p1, p2) => p1.age - p2.age))
控制台输出
[
Person { name: 'N', age: 20 },
Person { name: 'T', age: 23 },
Person { name: 'Y', age: 32 }
]