sort 和 toSorted - JS


Jan 27, 2025

Array.sort()

Sort會改變原本的array排序

const months = ['March', 'Jan', 'Feb', 'Dec'];
months.sort();
console.log(months);
// Expected output: Array ["Dec", "Feb", "Jan", "March"]

const array1 = [1, 30, 4, 21, 100000];
array1.sort();
console.log(array1);
// Expected output: Array [1, 100000, 21, 30, 4]

Global_Objects/Array/sort - MDN

Array.toSorted()

還沒有實際在工作上用到,但是看起來蠻好的一個方法,和 .sort() 的差別是 .toSorted 不會修改原本的array,會回傳排序完成的副本,更加符合immutable的精神!

toSorted 雖然是一個相對新的方法,但從2023年7月開始各大瀏覽器的支援也蠻完整的了
Can I Use: toSorted

const months = ["Mar", "Jan", "Feb", "Dec"];
const sortedMonths = months.toSorted();
console.log(sortedMonths); // ['Dec', 'Feb', 'Jan', 'Mar']
console.log(months); // ['Mar', 'Jan', 'Feb', 'Dec']

const values = [1, 10, 21, 2];
const sortedValues = values.toSorted((a, b) => a - b);
console.log(sortedValues); // [1, 2, 10, 21]
console.log(values); // [1, 10, 21, 2]

Global_Objects/Array/toSorted - MDN

#js #Array






你可能感興趣的文章

網路溝通、HTTP 協定

網路溝通、HTTP 協定

邊上班邊跟課的同學很厲害~時間好珍貴啊QQ

邊上班邊跟課的同學很厲害~時間好珍貴啊QQ

實作 PHP API & 留言板 SPA(下)

實作 PHP API & 留言板 SPA(下)






留言討論