陣列除了新增與刪除,也常需要合併與排序。JavaScript 提供 concat()、sort() 與 reverse() 等方法來處理這些操作。
concat() 會回傳新陣列,不會修改原陣列。
const hege = ['Cecilie', 'Lone'];
const stale = ['Emil', 'Tobias', 'Linus'];
const children = hege.concat(stale);
console.log(children);
也可以一次合併多個陣列:
const parents = ['Jani', 'Tove'];
const brothers = ['Stale', 'Kai Jim', 'Borge'];
const kids = ['Cecilie', 'Lone'];
const family = parents.concat(brothers, kids);
sort() 預設會依字串順序排序:
const fruits = ['Banana', 'Orange', 'Apple', 'Mango'];
fruits.sort();
console.log(fruits);
若要依數字大小排序,需要傳入比較函式:
const points = [40, 100, 1, 5, 25, 10];
points.sort(function (a, b) {
return a - b;
});
points.sort(function (a, b) {
return b - a;
});
reverse() 會反轉陣列元素順序:
fruits.reverse();
console.log(fruits);