functioncompare(a, b) { if (a is less than b by some ordering criterion) { return-1; } if (a is greater than b by the ordering criterion) { return1; } // a must be equal to b return0; }
正向排序與反向排序 function 的寫法
排序方式
js
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
// 正向排序 functioncompareNumbers(a, b) { return a - b; }
// 反向排序 functioncompareNumbers(a, b) { return b - a; }
// 使用方式 var numbers = [4, 2, 5, 1, 3]; numbers.sort(function(a, b) { return a - b; }); console.log(numbers); // [1, 2, 3, 4, 5]
// sort by name items.sort(function(a, b) { var nameA = a.name.toUpperCase(); // ignore upper and lowercase var nameB = b.name.toUpperCase(); // ignore upper and lowercase if (nameA < nameB) { return-1; } if (nameA > nameB) { return1; }