信息发布→ 登录 注册 退出

Javascript如何实现排序_如何自定义比较函数?

发布时间:2025-12-19

点击量:
Array.prototype.sort()默认按字符串Unicode码点排序,数字数组需用(a,b)=>a-b升序或b-a降序;对象数组可按属性用减法或localeCompare排序,多级排序用逻辑或实现优先级。

JavaScript 中的 Array.prototype.sort() 默认按字符串 Unicode 码点排序,直接对数字数组使用会导致 [10, 2, 33, 4] 排成 [10, 2, 33, 4](因为转成字符串后 "10"

比较函数的基本规则

比较函数接收两个参数 ab,返回一个数字:

  • 返回值 :表示 a 应排在 b 前面
  • 返回值 === 0:表示 ab 位置不变(相等)
  • 返回值 > 0:表示 a 应排在 b 后面

最简写法就是 (a, b) => a - b(升序),(a, b) => b - a(降序)——仅适用于数字。

对数字数组升序/降序

直接用减法最安全高效:

[5, 1, 9, 3].sort((a, b) => a - b);     // [1, 3, 5, 9]
[5, 1, 9, 3].sort((a, b) => b - a);     // [9, 5, 3, 1]

⚠️注意:不要写成 return a > b,那返回布尔值,会被转为 0 或 1,导致错误排序。

对对象数组按属性排序

比如按用户年龄升序,或按姓名字母序(忽略大小写):

const users = [
  { name: 'Alice', age: 32 },
  { name: 'bob', age: 25 },
  { name: 'Charlie', age: 28 }
];

// 按 age 升序 users.sort((a, b) => a.age - b.age);

// 按 name 字母序(不区分大小写) users.sort((a, b) => a.name.toLowerCase().localeCompare(b.name.toLowerCase()));

String.prototype.localeCompare() 是推荐的字符串比较方法,比 a.name > b.name 更可靠,能正确处理中文、重音字符等。

多级排序(先按 A,再按 B)

用逻辑或 || 实现优先级:第一级相等时才比较第二级:

const items = [
  { category: 'fruit', price: 3.5 },
  { category: 'veg',   price: 2.1 },
  { category: 'fruit', price: 2.9 }
];

// 先按 category 升序,category 相同时按 price 升序 items.sort((a, b) => { const catDiff = a.category.localeCompare(b.category); return catDiff !== 0 ? catDiff : a.price - b.price; });

这种结构清晰、可读性强,也容易扩展到三级或更多级。

标签:# javascript  # java  # go  
在线客服
服务热线

服务热线

4008888355

微信咨询
二维码
返回顶部
×二维码

截屏,微信识别二维码

打开微信

微信号已复制,请打开微信添加咨询详情!