2026年4月27日 星期一

再探 Array.toSorted()

 再探 Array.toSorted()

前言

  在先前 初探 Array.toSorted() 介紹 Array.toSorted() ,Array.toSorted()可以支援更換比較方法,但實際使用後有一些根想的不一樣,在此把學習的過程做個紀錄。


內容

  範例如下

let ar = ["Jan", "Feb", "Mar", "Apr"];
let numAr = [ 1 , 3 , 2 , 4 ];
//
console.log( ar.toSorted() );//["Apr", "Feb", "Jan", "Mar"]
console.log( ar.toSorted( (a , b) => a.toLowerCase().localeCompare(b.toLowerCase() ) ) );//["Apr", "Feb", "Jan", "Mar"]
console.log( ar.toSorted( (a , b) => b.toLowerCase().localeCompare(a.toLowerCase() ) ) );//["Mar", "Jan", "Feb", "Apr"]
//

console.log( numAr.toSorted() );//[1, 2, 3, 4]
console.log( numAr.toSorted( ( a , b ) => a - b) );//[1, 2, 3, 4]
console.log( numAr.toSorted( ( a , b ) => b - a) );//[4, 3, 2, 1]


只要再輸入比較方法就可更換比較方法,不過根想得不太一樣,不一樣的是比較手段不是用大於小於,而是字串與數字有各自的預設的比較手段,範例都是先預設比較,在替代等效預設比較,再來替代成跟預設比較相反的結果。


參考資料

[ developer.mozilla.org ] Array.prototype.toSorted()


相關文章與資料

初探 Array.toSorted()

沒有留言:

張貼留言