公司动态

HarmonyOS应用开发实战:猫猫大作战-排序算法与奖品排序

📅 2026/7/29 15:16:09
HarmonyOS应用开发实战:猫猫大作战-排序算法与奖品排序
前言在「猫猫大作战」的排行榜和合成结果展示中排序是基础能力。ArkTS 的数组sort()方法用于对数组元素排序但默认按字符串 ASCII 码排序——对数字排序需要传入比较函数。本文以排行榜的排序实现为锚点讲解数组排序的完整使用。一、基础排序// 默认排序字符串顺序 — 对数字表现异常 const nums [1, 30, 4, 21, 100]; nums.sort(); // [1, 100, 21, 30, 4] ❌ // 正确传入比较函数 nums.sort((a, b) a - b); // [1, 4, 21, 30, 100] ✅ nums.sort((a, b) b - a); // [100, 30, 21, 4, 1] ✅二、对象数组排序interface LeaderboardEntry { playerName: string; score: number; duration: number; gameDate: string; } // 按得分降序 const sorted entries.sort((a, b) b.score - a.score); // 复合排序得分降序同分按用时升序 const sorted2 entries.sort((a, b) { if (a.score ! b.score) return b.score - a.score; return a.duration - b.duration; // 同分用时短的靠前 });排序方式比较函数场景升序a - b数字从小到大降序b - a排行榜得分字符串升序a.localeCompare(b)玩家姓名日期降序new Date(b) - new Date(a)最新记录三、游戏中的排行榜排序function sortLeaderboard(entries: LeaderboardEntry[]): LeaderboardEntry[] { return [...entries].sort((a, b) { // 一级排序得分降序 if (a.score ! b.score) return b.score - a.score; // 二级排序时长升序 if (a.duration ! b.duration) return a.duration - b.duration; // 三级排序日期升序先完成的排名靠前 return new Date(a.gameDate).getTime() - new Date(b.gameDate).getTime(); }); }四、性能考虑// 小数据量 1000直接使用 sort()时间复杂度 O(n log n) // 大数据量 10000考虑使用后端排序或索引 // 缓存排序结果 private sortedCache: LeaderboardEntry[] | null null; private lastSortKey: string ; getSortedLeaderboard(): LeaderboardEntry[] { const key this.entries.map(e e.score).join(,); if (key this.lastSortKey this.sortedCache) { return this.sortedCache; // 数据未变返回缓存 } this.sortedCache sortLeaderboard(this.entries); this.lastSortKey key; return this.sortedCache; }五、常见错误错误表现原因修复默认 sort数字排序错误字符串比较传入比较函数修改原数组数据混乱sort 会修改原数组[...arr].sort()浮点数比较精度误差用a - b对浮点数比较差值绝对值总结ArkTS 的sort()方法配合比较函数实现排行榜和历史记录的灵活排序。核心要点数字排序必须传入比较函数、 复合排序链式条件、 不修改原数组[...arr].sort()、 大数据量用后端排序。如果这篇文章对你有帮助欢迎点赞、收藏⭐、关注你的支持是我持续创作的动力相关资源Array.sort() MDN 文档GameEngine 排行榜源码第 122 篇collision第 124 篇forEach update