承上一篇,這次看升冪。JS 陣列的 sort 方法接受一個函式作為參數,用來定義自訂的排序規則;只要回傳 a - b,就能讓數字由小到大排列。
<!DOCTYPE html>
<html>
<body>
<p id="demo">Click the button to sort the array.</p>
<button onclick="myFunction()">Try it</button>
<script>
function myFunction() {
var points = [40, 100, 1, 5, 25, 10];
points.sort(function (a, b) { return a - b; });
var x = document.getElementById("demo");
x.innerHTML = points;
}
</script>
</body>
</html>
輸出:
1,5,10,25,40,100
若不傳,sort() 會把每個元素轉成字串再依 UTF-16 編碼順序比較,於是:
[40, 100, 1, 5, 25, 10].sort(); // [1, 10, 100, 25, 40, 5] ← 顯然不是我們要的
因為字典序下 "10" 排在 "25" 前面、"100" 排在 "5" 前面。這不是 bug,而是刻意設計——預設行為要對所有型別一致,字串排序才是它的本職。
points.sort((a, b) => a - b); // 升冪 points.sort((a, b) => b - a); // 降冪 [...points].sort((a, b) => a - b); // 不改動原陣列
記住 sort() 是原地排序(in-place),會改動原陣列並回傳同一個陣列參照。需要保留原始資料時,務必先淺拷貝再排。