File tree Expand file tree Collapse file tree 1 file changed +0
-16
lines changed
1-js/05-data-types/05-array-methods/8-sort-objects Expand file tree Collapse file tree 1 file changed +0
-16
lines changed Original file line number Diff line number Diff line change @@ -16,19 +16,3 @@ alert(arr[0].name); // John
16
16
alert (arr[1 ].name ); // Mary
17
17
alert (arr[2 ].name ); // Pete
18
18
```
19
-
20
- 译注:解决方案的代码还可以更短一些
21
-
22
- ``` js
23
- function sortByAge (arr ) {
24
- arr .sort ((a , b ) => a .age - b .age );
25
- }
26
- ```
27
-
28
- 因为 ` sort() ` 方法的语法为 ` arr.sort([compareFunction]) ` ,如果没有指明 ` compareFunction ` ,那么元素会被按照转换为的字符串的诸个字符的 Unicode 编码进行排序,如果指明了 ` compareFunction ` ,那么数组会按照调用该函数的返回值排序。即 ` a ` 和 ` b ` 是两个将要被比较的元素:
29
-
30
- - 如果 ` compareFunction(a, b) ` 小于 ` 0 ` ,那么 ` a ` 会被排列到 ` b ` 之前;
31
- - 如果 ` compareFunction(a, b) ` 等于 ` 0 ` ,那么 ` a ` 和 ` b ` 的相对位置不变。备注:ECMAScript 标准并不保证这一行为,而且也不是所有浏览器都会遵守(例如 Mozilla 在 2003 年之前的版本);
32
- - 如果 ` compareFunction(a, b) ` 大于 ` 0 ` ,那么 ` b ` 会被排列到 ` a ` 之前。
33
-
34
- 因此,升序排列的函数可以简写为:` (a, b) => a.age - b.age ` 。
You can’t perform that action at this time.
0 commit comments