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 前面
a 和 b 位置不变(相等)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 }
];
<p>// 按 age 升序
users.sort((a, b) => a.age - b.age);</p><p>// 按 name 字母序(不区分大小写)
users.sort((a, b) => a.name.toLowerCase().localeCompare(b.name.toLowerCase()));String.prototype.localeCompare() 是推荐的字符串比较方法,比 a.name > b.name 更可靠,能正确处理中文、重音字符等。
用逻辑或 || 实现优先级:第一级相等时才比较第二级:
const items = [
{ category: 'fruit', price: 3.5 },
{ category: 'veg', price: 2.1 },
{ category: 'fruit', price: 2.9 }
];
<p>// 先按 category 升序,category 相同时按 price 升序
items.sort((a, b) => {
const catDiff = a.category.localeCompare(b.category);
return catDiff !== 0 ? catDiff : a.price - b.price;
});这种结构清晰、可读性强,也容易扩展到三级或更多级。
以上就是Javascript如何实现排序_如何自定义比较函数?的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号