陣列操作(Array Methods)#

陣列(Array)是 JavaScript 中最常用的資料結構,用來儲存有序的多個值,大小動態調整,且可混合儲存不同型別。 除了基本的存取操作,mapfilterreduce 等高階方法讓資料轉換與計算更為簡潔。


建立陣列#

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
const fruits = ["蘋果", "香蕉", "橘子"];
const nums = [1, 2, 3, 4, 5];
const mixed = [1, "hello", true, null];

// 透過 Array 建構函式
const zeros = new Array(3).fill(0); // [0, 0, 0]

// Array.from
const chars = Array.from("hello");  // ["h", "e", "l", "l", "o"]
const range = Array.from({ length: 5 }, (_, i) => i + 1); // [1, 2, 3, 4, 5]

存取與基本操作#

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
const arr = ["a", "b", "c", "d"];

// 存取元素(索引從 0 開始)
console.log(arr[0]);    // "a"
console.log(arr.at(-1)); // "d"(負數索引,ES2022)

// 長度
console.log(arr.length); // 4

// 加入元素
arr.push("e");      // 加到末尾 → ["a","b","c","d","e"]
arr.unshift("z");   // 加到開頭 → ["z","a","b","c","d","e"]

// 移除元素
arr.pop();          // 移除末尾 → 回傳 "e"
arr.shift();        // 移除開頭 → 回傳 "z"

常用方法速查#

方法說明是否修改原陣列
push / pop末尾加入/移除
unshift / shift開頭加入/移除
splice刪除/插入元素
sort排序
map轉換每個元素否(回傳新陣列)
filter篩選元素
reduce累積計算
slice取子陣列
find找第一個符合元素
includes判斷元素是否存在

map — 轉換每個元素#

1
2
3
4
5
6
7
8
const nums = [1, 2, 3, 4, 5];

const doubled = nums.map(n => n * 2);
console.log(doubled); // [2, 4, 6, 8, 10]

const words = ["hello", "world"];
const upper = words.map(w => w.toUpperCase());
console.log(upper); // ["HELLO", "WORLD"]

map 回傳新陣列,不修改原陣列


filter — 篩選元素#

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
const nums = [1, 2, 3, 4, 5, 6];

const evens = nums.filter(n => n % 2 === 0);
console.log(evens); // [2, 4, 6]

const users = [
    { name: "Alice", age: 25 },
    { name: "Bob", age: 17 },
    { name: "Carol", age: 30 }
];

const adults = users.filter(u => u.age >= 18);
// [{ name: "Alice", age: 25 }, { name: "Carol", age: 30 }]

reduce — 累積計算#

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
const nums = [1, 2, 3, 4, 5];

// 加總
const sum = nums.reduce((acc, n) => acc + n, 0);
console.log(sum); // 15

// 找最大值
const max = nums.reduce((a, b) => a > b ? a : b);
console.log(max); // 5

// 統計出現次數
const words = ["apple", "banana", "apple", "cherry", "banana", "apple"];
const count = words.reduce((acc, word) => {
    acc[word] = (acc[word] || 0) + 1;
    return acc;
}, {});
console.log(count); // { apple: 3, banana: 2, cherry: 1 }

find / findIndex — 尋找元素#

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
const users = [
    { id: 1, name: "Alice" },
    { id: 2, name: "Bob" },
    { id: 3, name: "Carol" }
];

// find — 回傳第一個符合的元素
const user = users.find(u => u.id === 2);
console.log(user); // { id: 2, name: "Bob" }

// findIndex — 回傳第一個符合的索引
const idx = users.findIndex(u => u.name === "Carol");
console.log(idx); // 2

some / every — 條件判斷#

1
2
3
4
5
6
7
8
const nums = [1, 3, 5, 7, 8];

// some — 至少一個符合
console.log(nums.some(n => n % 2 === 0));  // true(8 是偶數)

// every — 全部符合
console.log(nums.every(n => n > 0));       // true
console.log(nums.every(n => n % 2 !== 0)); // false(8 是偶數)

flat / flatMap — 展平陣列#

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
const nested = [1, [2, 3], [4, [5, 6]]];

console.log(nested.flat());    // [1, 2, 3, 4, [5, 6]](展平一層)
console.log(nested.flat(2));   // [1, 2, 3, 4, 5, 6](展平兩層)
console.log(nested.flat(Infinity)); // 完全展平

// flatMap — map 後再展平一層
const sentences = ["hello world", "foo bar"];
const words = sentences.flatMap(s => s.split(" "));
console.log(words); // ["hello", "world", "foo", "bar"]

sort — 排序#

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
const letters = ["banana", "apple", "cherry"];
letters.sort();
console.log(letters); // ["apple", "banana", "cherry"]

// 數字排序需提供比較函式
const nums = [10, 1, 21, 2];
nums.sort((a, b) => a - b);  // 升冪
console.log(nums); // [1, 2, 10, 21]

nums.sort((a, b) => b - a);  // 降冪
console.log(nums); // [21, 10, 2, 1]

sort修改原陣列,若需保留原陣列用 [...arr].sort(...)


slice / splice#

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
const arr = ["a", "b", "c", "d", "e"];

// slice — 取子陣列(不修改原陣列)
console.log(arr.slice(1, 3));  // ["b", "c"]
console.log(arr.slice(-2));    // ["d", "e"]

// splice — 刪除/插入元素(修改原陣列)
arr.splice(2, 1);           // 從索引 2 刪除 1 個元素
console.log(arr);           // ["a", "b", "d", "e"]

arr.splice(2, 0, "X", "Y"); // 在索引 2 插入,不刪除
console.log(arr);           // ["a", "b", "X", "Y", "d", "e"]

Reference#