es6 reduce函数
时间: 2023-11-02 11:01:37 浏览: 45
reduce() 是 ES6 中的一个数组方法,它接收一个函数作为累加器,用来对数组中的每个元素进行累加操作,并最终返回一个结果值。reduce() 方法接受四个参数:初始值、累加器函数、当前值、当前索引和当前数组。累加器函数会被依次应用于数组中的每个元素,从左到右进行累加计算。在每一次调用累加器函数时,它会接收两个参数:上一次累加的结果值和当前元素的值。reduce() 方法的返回值就是累加的结果。
下面是一个例子来说明 reduce() 的使用:
```
let arr = [1, 2, 3, 4, 5];
let sum = arr.reduce((previousValue, currentValue) => previousValue + currentValue, 0);
console.log(sum); // 输出 15
```
在这个例子中,我们使用 reduce() 对数组 arr 中的元素进行累加操作。初始值为 0,累加器函数将上一次累加的结果值和当前元素的值相加,得到最终的结果值 15。
相关问题
es6 reduce
reduce()是ES6中的一个非常强大的数组方法。它接收一个函数作为累加器,在数组中的每个值上进行迭代,并将多个值缩减为一个值。reduce()方法接受四个参数:初始值、累加器函数、当前值和当前索引。累加器函数有两个参数,第一个参数是累加器的值(也称为累计值),第二个参数是当前值。累加器函数在每次迭代中将累加器的值与当前值进行操作,并返回一个新的累加器值。最终,reduce()方法返回累加器的最终值。
让我们来看一些示例:
1. 数组求和、求乘积:
```javascript
let arr = [1, 2, 3, 4];
let sum = arr.reduce((x, y) => x + y);
let mul = arr.reduce((x, y) => x * y);
console.log(sum); // 求和,10
console.log(mul); // 求乘积,24
```
2. 多维数组转一维数组:
```javascript
let arr = [[0, 1], [2, 3], [4, [5, 6, 7]]];
const newArr = function(arr) {
return arr.reduce((pre, cur) => pre.concat(Array.isArray(cur) ? newArr(cur) : cur), []);
}
console.log(newArr(arr)); // [0, 1, 2, 3, 4, 5, 6, 7]
```
利用ES5和ES6求函数参数的和
在5中,可以使用``对象来获取函数的参数列表,并通过遍历实现求和。示例代码如下:
```javascript
function sum() {
var total = 0;
for (var i = 0; i < arguments.length; i++) {
total += arguments[i];
}
return total;
}
console.log(sum(1, 2, 3)); // 输出6
```
在ES6中,可以使用剩余参数(rest parameters)来获取函数的参数列表,并通过数组的`reduce`方法求和。示例代码如下:
```javascript
function sum(...args) {
return args.reduce((acc, curr) => acc + curr, 0);
}
console.log(sum(1, 2, 3)); // 输出6
```
这两种方法都可以用来求函数参数的和,选择使用哪种取决于你的项目需求和对语言版本的要求。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)