# 章序号/节序号/节/笔记序号 codecademy, Iterators # 概念阐释 ## 语义 **`reduce()`** 方法逐个遍历数组元素,求和。 ## 语法 ``` //箭头函数 reduce((previousValue, currentValue) => { /* … */ } ) // 内联回调函数 reduce(function(previousValue, currentValue) { /* … */ }) ``` # 举例子 - **accumulator是回调函数,console accumulator 就能看到运算过程** ```js const numbers = [1, 2, 4, 10]; const summedNums = numbers.reduce((accumulator, currentValue) => {   return accumulator + currentValue }) console.log(summedNums) // Output: 17 ``` ![](http://image.harryrou.wiki/2023-03-08-%E6%88%AA%E5%B1%8F2023-03-08%2008.39.09.png) ## 数组➕100 ```js const numbers = [1, 2, 4, 10]; const summedNums = numbers.reduce((accumulator, currentValue) => {   return accumulator + currentValue }, 100)  // <- Second argument for .reduce() console.log(summedNums); // Output: 117 ``` - **accumulator是回调函数** ![](http://image.harryrou.wiki/2023-03-08-%E6%88%AA%E5%B1%8F2023-03-08%2008.05.02.png) # 类比、比较与对比 # 问题 1. [完成codecademy课后练习题 - reduce()](https://www.codecademy.com/courses/introduction-to-javascript/lessons/javascript-iterators/exercises/reduce) 🌟🌟 1. 用`.reduce()`返回结果,并加上10 2. [完成codecademy课后练习题 - 更多数组函数内置对象练习](https://www.codecademy.com/courses/introduction-to-javascript/lessons/javascript-iterators/exercises/documentation)🌟🌟 ```js //练习题2步骤 //在代码编辑器中,有一个名为words的数组。我们想要创建一个新的有趣单词数组。我们首先想要做的是检查是否有少于6个字符的单词。在words.some()方法调用中有一些缺失。修复这个方法,使得true被打印到控制台中。 //.some() 方法返回 true,这意味着数组中有一些单词少于六个字符。 使用 .filter() 方法将任何超过 5 个字符的单词保存到一个名为 interestingWords 的新变量中,该变量用 const 声明。 我们在之前的练习中使用了 .filter() ,但是,有关更多信息,请浏览 MDN 关于 .filter() 的文档。 //在括号内完成代码以检查每个元素是否具有超过5个字符,使用.every ``` # 问题答案 1. ```js const newNumbers = [1, 3, 5, 7]; const newSum = newNumbers.reduce((accumulator, currentValue) => { console.log('The value of accumulator: ', accumulator); console.log('The value of currentValue: ', currentValue); return accumulator + currentValue; }, 10); console.log(newSum); ``` 2. ```js const words = ['unique', 'uncanny', 'pique', 'oxymoron', 'guise']; // Something is missing in the method call below console.log(words.some(word => { return word.length < 6; })); // Use filter to create a new array const interestingWords = words.filter( longwords => { return longwords.length > 5; } ); console.log(interestingWords); // Make sure to uncomment the code below and fix the incorrect code before running it console.log(interestingWords.every(word => word>5 )); ``` # 备注(经验集/错误集) ## 经验集 ## 错误集 - *` .every()` 如果用MDN的写法会出错,因为顺序是颠倒的。* - 数组内置对象中的方法的函数写法 => 后面是`{}` ## 参考资料