The JavaScript Array Methods Handbook
健忘的 Sean 常常需要查看的陣列處理方法小抄。
What will this method return
- 單純遞迴執行:
forEach
- 回傳一個新的陣列:
map
、filter
、concat
- 回傳一個布林值:
some
、every
、includes
- 回傳該元素:
find
- 回傳該索引:
findIndex
、indexOf
- 回傳一個整數值:
reduce
、unshift
forEach
將陣列裡的每個元素傳入,並「執行」給定的函式一次。
1const array1 = ['a', 'b', 'c']; 2 3array1.forEach((element) => console.log(element)); 4 5// Expected output: "a" 6// Expected output: "b" 7// Expected output: "c" 8
map
原陣列的每一個元素經過指定的函式「運算」後,回傳新的結果陣列。
1const array1 = [1, 2, 3, 4]; 2 3// Pass a function to map 4const result = array1.map((x) => x * 2); 5 6console.log(result); 7// Expected output: Array [2, 4, 6, 8] 8
filter
原陣列經過指定的函式「過濾」後,回傳新的結果陣列。
1const words = ['Sean', 'Damao', 'Paul', 'Iris', 'Julia']; 2 3const result = words.filter((word) => word.length > 4); 4 5console.log(result); 6// Expected output: Array ["Damao", "Julia"] 7
concat
合併兩個或多個陣列,回傳一個新的陣列。
1const array1 = ['a', 'b', 'c']; 2const array2 = ['d', 'e', 'f', 'g']; 3const array3 = array1.concat(array2); 4 5console.log(array3); 6// Expected output: Array ["a", "b", "c", "d", "e", "f", "g"] 7
some
測試陣列中,是否有「至少一個」元素符合指定的條件函式,是的話會回傳 true
否則回傳 false
。
1const array1 = [1, 2, 3, 5, 7]; 2 3// Checks whether an element is even 4const isEven = (element) => element % 2 === 0; 5 6console.log(array1.some(isEven)); 7// Expected output: true 8
every
回傳是否陣列中的「所有」元素都符合條件。
1const array1 = [2, 4, 6, 8, 10]; 2 3// Checks whether all elements are even 4const areEven = (element) => element % 2 === 0; 5 6console.log(array1.every(areEven)); 7// Expected output: true 8
includes
回傳陣列是否「包含」指定的元素。
1const pets = ['cat', 'dog']; 2 3console.log(pets.includes('cat')); 4// Expected output: true 5 6console.log(pets.includes('pig')); 7// Expected output: false 8
find
回傳「第一個」滿足條件的元素,如果通通不符合則回傳 undefined
。
1const array1 = [5, 6, 8, 100, 44]; 2 3const found = array1.find((element) => element > 10); 4 5console.log(found); 6// Expected output: 100 7
findIndex
回傳「第一個」滿足條件的元素之「索引」,如果找不到則回傳 -1
。
1const array1 = [5, 6, 8, 100, 44]; 2 3const isLargeNumber = (element) => element > 8; 4 5console.log(array1.findIndex(isLargeNumber)); 6// Expected output: 3 7
indexOf
回傳「指定的元素」在陣列中「第一個」被找到的「索引」,如果找不到則回傳 -1
。
1const beasts = ['squirrel', 'seal', 'cat', 'duck', 'rabbit']; 2 3console.log(beasts.indexOf('squirrel')); 4// Expected output: 0 5 6// Start from index 2 7console.log(beasts.indexOf('seal', 2)); 8// Expected output: 4 9 10console.log(beasts.indexOf('pig')); 11// Expected output: -1 12
reduce
將陣列中的每一項元素「由左至右」傳入「累加器」,最後回傳一個值。
1const array1 = [1, 2, 3, 4]; 2 3// 0 + 1 + 2 + 3 + 4 4const initialValue = 0; 5const sumWithInitial = array1.reduce( 6 (accumulator, currentValue) => accumulator + currentValue, 7 initialValue, 8); 9 10console.log(sumWithInitial); 11// Expected output: 10 12
unshift
unshift()
會增加一個或多個元素到陣列的開頭,並且回傳陣列的新長度。
1const array1 = [1, 2, 3]; 2 3console.log(array1.unshift(4, 5)); 4// Expected output: 5 5 6console.log(array1); 7// Expected output: Array [4, 5, 1, 2, 3] 8