登录
首页 >  文章 >  前端

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

时间:2026-05-24 16:38:10 367浏览 收藏

哈喽!大家好,很高兴又见面了,我是golang学习网的一名作者,今天由我给大家带来一篇《Javascript如何实现排序_如何自定义比较函数?》,本文主要会讲到等等知识点,希望大家一起学习进步,也欢迎大家关注、点赞、收藏、转发! 下面就一起来看看吧!

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

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

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

比较函数的基本规则

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

  • 返回值 < 0:表示 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 }
];
<p>// 按 age 升序
users.sort((a, b) => a.age - b.age);</p><p>// 按 name 字母序(不区分大小写)
users.sort((a, b) => a.name.toLowerCase().localeCompare(b.name.toLowerCase()));</p>

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

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

今天带大家了解了的相关知识,希望对你有所帮助;关于文章的技术知识我们会一点点深入介绍,欢迎大家关注golang学习网公众号,一起学习编程~

资料下载
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>