1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
const users = [
{ name: 'aqing', age: 24 },
{ name: 'ale', age: 21 },
{ name: 'bei', age: 25 },
];

//按照name比较
const usersSortedByName = users.sort((a, b) => a.name.localeCompare(b.name));
console.log(usersSortedByName);
/*
(3) […]
0: Object { name: "ale", age: 21 }
1: Object { name: "aqing", age: 24 }
2: Object { name: "bei", age: 25 }
length: 3
*/

// 按照age比较
const usersSortedByAge = users.sort((a, b) => a.age - b.age);
console.log(usersSortedByAge);
/*
(3) […]
0: Object { name: "ale", age: 21 }
1: Object { name: "aqing", age: 24 }
2: Object { name: "bei", age: 25 }
length: 3
*/