1.相同點:
- 都會循環遍歷數組中的每一項;
- map()、forEach()和filter()方法里每次執行匿名函數都支持3個參數,參數分別是:當前元素、當前元素的索引、當前元素所屬的數組;
- 匿名函數中的this都是指向window;
- 只能遍歷數組。
2.不同點:
- map()速度比forEach()快;
- map()和filter()會返回一個新數組,不對原數組產生影響;forEach()不會產生新數組,返回undefined;reduce()函數是把數組縮減為一個值(比如求和、求積);
- reduce()有4個參數,第一個參數為初始值。
3.forEach使用
var array1 = ['a', 'b', 'c']; array1.forEach(function(element) { console.log(element); });
4.map使用
var array1 = [1, 4, 9, 16]; // pass a function to map const map1 = array1.map(x => x * 2); console.log(map1); // expected output: Array [2, 8, 18, 32]
5.filter使用
var words = ['spray', 'limit', 'elite', 'exuberant', 'destruction', 'present']; const result = words.filter(word => word.length > 6); console.log(result); // expected output: Array ["exuberant", "destruction", "present"]
6.reduce使用
const array1 = [1, 2, 3, 4]; const reducer = (accumulator, currentValue) => accumulator + currentValue; // 1 + 2 + 3 + 4 console.log(array1.reduce(reducer)); // expected output: 10 // 5 + 1 + 2 + 3 + 4 console.log(array1.reduce(reducer, 5)); // expected output: 15
