Skip to content

fix: delete outdated annotations #1187

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Jun 30, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 0 additions & 16 deletions 1-js/05-data-types/05-array-methods/8-sort-objects/solution.md
Original file line number Diff line number Diff line change
Expand Up @@ -16,19 +16,3 @@ alert(arr[0].name); // John
alert(arr[1].name); // Mary
alert(arr[2].name); // Pete
```

译注:解决方案的代码还可以更短一些

```js
function sortByAge(arr) {
arr.sort((a, b) => a.age - b.age);
}
```

因为 `sort()` 方法的语法为 `arr.sort([compareFunction])`,如果没有指明 `compareFunction`,那么元素会被按照转换为的字符串的诸个字符的 Unicode 编码进行排序,如果指明了 `compareFunction`,那么数组会按照调用该函数的返回值排序。即 `a` 和 `b` 是两个将要被比较的元素:

- 如果 `compareFunction(a, b)` 小于 `0`,那么 `a` 会被排列到 `b` 之前;
- 如果 `compareFunction(a, b)` 等于 `0`,那么 `a` 和 `b` 的相对位置不变。备注:ECMAScript 标准并不保证这一行为,而且也不是所有浏览器都会遵守(例如 Mozilla 在 2003 年之前的版本);
- 如果 `compareFunction(a, b)` 大于 `0`,那么 `b` 会被排列到 `a` 之前。

因此,升序排列的函数可以简写为:`(a, b) => a.age - b.age`。