句法

`arr.reduce(callbackFunction, [initialValue])`

什么是减少做?

Reduce can be used, 例如, to total a shopping cart

例

```  让ARR = [1,2,3,4,5];
arr.reduce( (累加器, 当前值, CURRENTINDEX, 排列) => {
//一些操作;
返回的东西;
});
```

回调函数

1. 累加器 – 如果提供在第一循环或初始值的阵列的第一个元素. 那么前一个循环的返回值.
2. 当前值 – 阵列中的当前元素. Starts from the second element in the array ie. arr, when the initial value argument is not passed. If the initial value argument is passed then current value starts from the 1st element in the array arr.
3. CURRENTINDEX – 当前元素的索引.
4. 排列 – 整个阵列.

工作实例

```让ARR = [1,2,3,4,5];

arr.reduce(
(累加器, 当前值, CURRENTINDEX, 排列) => {
的console.log(`累加器 (On 1st loop, accumulator is arr, then it is the returned value of the previous loop): \${累加器}`);
的console.log(`CurrentValue的 (Loops through the array, starting at arr): \${当前值}`);
的console.log(`CURRENTINDEX: \${CURRENTINDEX}`);
的console.log(`阵列: \${排列}`);
的console.log('---');
回累加器 + 当前值;
}
);
```

产量

```累加器 (On 1st loop, accumulator is arr, then it is the returned value of the previous loop): 1

CURRENTINDEX: 1

---

CURRENTINDEX: 2

---

CURRENTINDEX: 3

---

CURRENTINDEX: 4

---
```

提供初始值

Note that the current value on the 1st loop now starts at the first element of the array

工作实例

```  让ARR = [1,2,3,4,5];

arr.reduce(
(累加器, 当前值, CURRENTINDEX, 排列) => {
的console.log(`累加器 ( On the 1st loop, this is the initial value, then the returned value of the previous loop): \${累加器}`);
的console.log(`CurrentValue的 (Loops through the array, starting at arr): \${当前值}`);
的console.log(`CURRENTINDEX: \${CURRENTINDEX}`);
的console.log(`阵列: \${排列}`);
的console.log('---');
回累加器 + 当前值;
}, 0
);
```

产量

```累加器 ( On the 1st loop, this is the initial value, then the returned value of the previous loop): 0

CURRENTINDEX: 0

---

CURRENTINDEX: 1

---

CURRENTINDEX: 2

---

CURRENTINDEX: 3

---

CURRENTINDEX: 4

---
```