From f47edc78927b0833d6c48f16b9c22135505d6b02 Mon Sep 17 00:00:00 2001 From: liangjiancang <42267675+liangjiancang@users.noreply.github.com> Date: Sun, 3 Oct 2021 03:12:17 +0800 Subject: Update Web/JavaScript/Reference/Global_Objects/Array/sort, zh-CN (#2611) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * 补充缺失的「Sort stability」部分 * 与原文 HTML 保持一致 * Fix:「可以会」→「可能会」 --- .../reference/global_objects/array/sort/index.html | 67 +++++++++++++++++----- 1 file changed, 53 insertions(+), 14 deletions(-) (limited to 'files/zh-cn/web/javascript/reference') diff --git a/files/zh-cn/web/javascript/reference/global_objects/array/sort/index.html b/files/zh-cn/web/javascript/reference/global_objects/array/sort/index.html index e9f9808420..e4140bde3b 100644 --- a/files/zh-cn/web/javascript/reference/global_objects/array/sort/index.html +++ b/files/zh-cn/web/javascript/reference/global_objects/array/sort/index.html @@ -114,20 +114,20 @@ items.sort(function (a, b) { return (a.value - b.value) }); -// sort by name -items.sort(function(a, b) { - var nameA = a.name.toUpperCase(); // ignore upper and lowercase - var nameB = b.name.toUpperCase(); // ignore upper and lowercase - if (nameA < nameB) { - return -1; - } - if (nameA > nameB) { - return 1; - } - - // names must be equal - return 0; -}); +// sort by name +items.sort(function(a, b) { + var nameA = a.name.toUpperCase(); // ignore upper and lowercase + var nameB = b.name.toUpperCase(); // ignore upper and lowercase + if (nameA < nameB) { + return -1; + } + if (nameA > nameB) { + return 1; + } + + // names must be equal + return 0; +});

示例

@@ -214,6 +214,45 @@ var result = mapped.map(function(el){ }); +

排序稳定性

+ +

自 ES10(EcmaScript 2019)起,规范 要求 Array.prototype.sort 为稳定排序。

+

假设有一个包含学生名字和年级的列表,已经将它按学生名字字母顺序进行预排序:

+
const students = [
+  { name: "Alex",   grade: 15 },
+  { name: "Devlin", grade: 15 },
+  { name: "Eagle",  grade: 13 },
+  { name: "Sam",    grade: 14 },
+];
+
+ +

对这个数组执行 grade 升序排序后:

+ +
students.sort((firstItem, secondItem) => firstItem.grade - secondItem.grade);
+
+ +

students 变量如下:

+ +
[
+  { name: "Eagle",  grade: 13 },
+  { name: "Sam",    grade: 14 },
+  { name: "Alex",   grade: 15 }, // grade 相同时维持原先的顺序 (稳定排序)
+  { name: "Devlin", grade: 15 }, // grade 相同时维持原先的顺序 (稳定排序)
+];
+
+ +

注意,那些年级相同的学生(如 Alex 和 Devlin)会维持调用排序之前的顺序,这是稳定排序所确保的。

+ +

ES10(EcmaScript 2019)以前没有要求稳定性,意味着你可能会得到以下结果:

+ +
[
+  { name: "Eagle",  grade: 13 },
+  { name: "Sam",    grade: 14 },
+  { name: "Devlin", grade: 15 }, // 没有维持原先的顺序
+  { name: "Alex",   grade: 15 }, // 没有维持原先的顺序
+];
+
+

规范

-- cgit v1.2.3-54-g00ecf