接續上篇【學習筆記】JavaScript 的陣列遍歷(ㄧ):for/for…of/for…in/forEach,這篇筆記整理幾種 JavaScript 遍歷陣列的方法,探討其使用時機與彼此的區別:
arr.forEach((value, index, array) => { // todo... })
arr.map(value => { // todo... })
arr.filter(value => { // todo... })
arr.every(value => { // todo... })
arr.some(value => { // todo... })
arr.reduce((acc, value)=> acc + value)
forEach:遍歷陣列,無返回值,會改變原來陣列
1 2 3
| array.forEach(function callback(currentValue, index?, array?){ }, thisArg?)
|
1 2 3 4 5 6 7
| let arr = [1, 3, 5, 11, -2, 8]; arr.forEach((item, index, array) => { array[index] = item * 2; });
console.log('arr: ', arr);
|
map:遍歷陣列,返回處理後的新陣列
1 2 3
| let newArray = arr.map(function callback( currentValue, index?, array?) { }, thisArg?)
|
- 使用範例:
- 常用於修改陣列中的資料格式,得到返回值後再執行後續動作
1 2 3 4 5 6 7
| let arr = [1, 3, 5, 11, -2, 8]; let newArr = arr.map(item => item * 2);
console.log('arr: ', arr); console.log('newArr ', newArr);
|
filter:篩選陣列中滿足條件的元素,並返回一個新陣列
1
| let newArray = arr.filter(callback(element, index, array), thisArg?)
|
1 2 3 4 5 6 7
| let arr = [1, 3, 5, 11, -2, 8]; let newArr = arr.filter(item => item < 5);
console.log('arr: ', arr); console.log('newArr: ', newArr);
|
every:判斷陣列中所有元素是否都滿足條件,返回一個布林值
1
| arr.every(callback, thisArg?)
|
1 2 3 4 5 6 7 8
| let arr = [1, 3, 5, 11, -2, 8]; let allSmallerThan10 = arr.every(x => x < 10); let allSmallerThan15 = arr.every(x => x < 15);
console.log('allSmallerThan10: ', allSmallerThan10); console.log('allSmallerThan15: ', allSmallerThan15);
|
some:判斷陣列中是否至少存在一個滿足條件的元素,返回一個布林值
1
| arr.some(callback, thisArg?)
|
1 2 3 4 5 6 7 8
| let arr = [1, 3, 5, 11, -2, 8]; let isBiggerThan10 = arr.some(x => x > 10); let isBiggerThan15 = arr.some(x => x > 15);
console.log('isBiggerThan10: ', isBiggerThan10); console.log('isBiggerThan15: ', isBiggerThan15);
|
reduce:將陣列中所有元素加總計算,返回一個總和
- callback 傳入參數:
- accumulator:目前累加值
- currentValue:目前執行到的元素值
- currentIndex:目前執行到的元素索引值
- array:陣列本身
- initialValue:初始累加值 => 若無指定則預設為 0
1 2 3 4
| arr.reduce( callback[accumulator, currentValue, currentIndex?, array?], initialValue? )
|
1 2 3 4 5 6 7 8 9 10 11 12 13
| let total = [1, 2, 3].reduce( (accumulator, currentValue) => { console.log('accumulator: ', accumulator); console.log('currentValue: ', currentValue); return accumulator + currentValue; } ); console.log('total: ', total);
|
參考資料
- 陣列遍歷的幾種用法—forEach()、map()、filter()、every()、some()
- Day09_Array的迭代方法