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”
比较函数的基本规则
比较函数接收两个参数 a 和 b,返回一个数字:
返回值 :表示 a 应排在 b 前面返回值 === 0:表示 a 和 b 位置不变(相等)返回值 > 0:表示 a 应排在 b 后面
最简写法就是 (a, b) => a - b(升序),(a, b) => b - a(降序)——仅适用于数字。
对数字数组升序/降序
直接用减法最安全高效:
立即学习“Java免费学习笔记(深入)”;
[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如何实现排序_如何自定义比较函数?的详细内容,更多请关注创想鸟其它相关文章!
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。
如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 chuangxiangniao@163.com 举报,一经查实,本站将立刻删除。
发布者:程序猿,转转请注明出处:https://www.chuangxiangniao.com/p/1544128.html
微信扫一扫
支付宝扫一扫