Skip to content
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

【JavaScript】使用 sort 对数组进行排序[3,15,8,29,102,22] #38

Closed
yayxs opened this issue Dec 24, 2020 · 0 comments
Closed

【JavaScript】使用 sort 对数组进行排序[3,15,8,29,102,22] #38

yayxs opened this issue Dec 24, 2020 · 0 comments

Comments

@yayxs
Copy link
Owner

yayxs commented Dec 24, 2020

使用 sort 对数组进行排序[3,15,8,29,102,22]

mdn 上的 sort

sort() 方法用原地算法对数组的元素进行排序,并返回数组。默认排序顺序是在将元素转换为字符串,然后比较它们的 UTF-16 代码单元值序列时构建的

  • 原地算法原地算法
  • 将元素转为字符串,这些元素默认情况下被按字符串进行排序
  • UTF-16

00.png

采用的utf-16 ,常见的字符数字 英语大小写 汉字,在数组内进行排序,并不会生成新数组,整体按照:数字》英语大写》英语小写》汉字

let target = ["你好世界", "HELLO", "hello", 666];

自定义排序的规则

const friends = [
  { name: "toM", age: 10 },
  { name: "JAn", age: 20 },
];

function compare(a, b) {
  if (a.age > b.age) {
    return 1;
  }
  if (a.age < b.age) {
    return -1;
  }
  return 0;
}

总结

	/**
     * Sorts an array.
     * @param compareFn Function used to determine the order of the elements. It is expected to return
     * a negative value if first argument is less than second argument, zero if they're equal and a positive
     * value otherwise. If omitted, the elements are sorted in ascending, ASCII character order.
     * ```ts
     * [11,2,22,1].sort((a, b) => a - b)
     * ```
     */
    sort(compareFn?: (a: T, b: T) => number): this;
  • 阮老师 字符编码

  • 步骤

    • 转为字符串 数字>英语大写>英语小写>汉字

    01.png

    • 对比第一个字符===>15 102 29 22 3 8
    • 对比第二个字符===>102 15 22 29 3 8
    • 对比第三个字符===>102 15 22 29 3 8
  • 案例

arr.sort((x, y) => {
  console.log(`排序:${x}----${y}`);
});
排序:15----3
排序:8----15
排序:29----8
排序:102----29
排序:22----102
arr.sort((x, y) => {
  console.log(`${x}-${y}=${x - y}`);
});
15-3=12
8-15=-7
29-8=21
102-29=73
22-102=-80
arr.sort((x, y) => {
  console.log(`${x}-${y}=${x - y}`);
  return x - y;
});
console.log(arr);
15-3=12
8-15=-7
8-15=-7
8-3=5
29-8=21
29-15=14
102-15=87
102-29=73
22-15=7
22-102=-80
22-29=-7
[ 3, 8, 15, 22, 29, 102 ]
  • 总结
    • 返回值小于 0 x 移动到 y 前 升序 return x-y
    • 返回值大于 0 x 移动到 y 后 降序 return y-x
    • 返回值等于 0 大多浏览器相对不变
  • 结果:

[ 102, 15, 22, 29, 3, 8 ]

@yayxs yayxs closed this as completed Feb 14, 2021
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant