FE Interview Hub
JavaScript 基礎

JavaScript 中的 sort 傳入 (a,b) ⇒ b - a 會是升序還是降序?為什麼呢?

AI 練習作答

答案

(a, b) => b - a 會讓陣列降序排列(從大到小)。

原理

Array.prototype.sort() 接受一個比較函式 compareFn(a, b),根據回傳值決定排序方式:

回傳值 行為
負數 a 排在 b 前面
0 順序不變
正數 b 排在 a 前面

分析 b - a

  • b > a,回傳正數b 排在前面 → 大的在前 → 降序
  • b < a,回傳負數a 排在前面 → 大的在前 → 降序
  • b === a,回傳 0 → 順序不變

範例

const arr = [3, 1, 4, 1, 5, 9, 2, 6];

// 升序 (a - b)
arr.sort((a, b) => a - b); // [1, 1, 2, 3, 4, 5, 6, 9]

// 降序 (b - a)
arr.sort((a, b) => b - a); // [9, 6, 5, 4, 3, 2, 1, 1]

記憶口訣

  • a - b升序(ascending,a 在前)
  • b - a降序(descending,b 在前)

✦ AI 模擬面試

輸入你的答案,AI 即時分析精準度與改進空間

登入後即可使用 AI 評分