JavaScript - 数组 .reduce() 方法
在 JavaScript 中,Array.reduce() 方法用于操作数组。此方法对数组的每个元素(从左到右)执行 Reducer 函数,并返回一个"单个值"作为结果。
它接受一个名为 'initialValue' 的可选参数。如果我们不将此参数传递给该方法,它将把 arr[0] 的值视为初始值。此外,它将对传递的 initialValue 参数执行回调函数。
此方法不会对空数组元素执行 Reducer 函数。除此之外,它不会修改原始数组。
注意 − 如果当前数组为空或不包含任何 initialValue,此方法将抛出 'TypeError' 异常。
语法
以下是 JavaScript Array.reduce() 方法的语法 −
reduce(callbackFn(accumulator, currentValue, currentIndex, array), initialValue)
参数
此方法接受两个参数。具体描述如下 −
-
callbackFn − 这是对数组中每个元素执行的函数。此函数接受四个参数:
- accumulator − 这是函数的初始值,即先前返回的值。
- currentValue − 这是数组中当前正在处理的元素。如果指定了 initialValue,则其值为 arr[0];否则,其值为 arr[1]。
- currentIndex(可选)- 这是当前正在处理的元素在数组中的索引。
- array(可选)- 这是调用 reduce() 方法的数组。
- initialValue(可选)- 首次调用回调函数时,累加器参数初始化的值。
返回值
此方法返回对数组进行 Reduce 后的结果。
示例
示例 1
在下面的示例中,我们使用 JavaScript Array.reduce() 方法对提供的数组中的所有元素求和。数组。
<html>
<body>
<script>
const numbers = [10, 20, 30, 40, 50];
const sum = numbers.reduce((accumulator, currentValue) => accumulator + currentValue, 0);
document.write(sum);
</script>
</body>
</html>
累加器从 0 开始,对于数组中的每个元素,它将当前元素添加到累加器中。累加器的最终结果 (150) 是所有元素的总和。
输出
150
示例 2
在此示例中,我们计算指定数组中所有元素的乘积 -
<html>
<body>
<script>
const numbers = [10, 20, 30, 40, 50];
const product = numbers.reduce((accumulator, currentValue) => accumulator * currentValue, 1);
document.write(product);
</script>
</body>
</html>
累加器从 1 开始,对于数组中的每个元素,它将当前元素乘以累加器。累加器的最终结果 (12000000) 是所有元素的乘积。
输出
12000000
示例 3
在下面的示例中,我们将一个包含数组的数组 (nesetedArray) 展平为一个一维数组 (flattenedArray) -
<html>
<body>
<script>
const nestedArray = [[1, 2], [3, 4], [5, 6]];
const flattenedArray = nestedArray.reduce((accumulator, currentValue) => accumulator.concat(currentValue), []);
document.write(flattenedArray);
</script>
</body>
</html>
输出
1,2,3,4,5,6
示例 4
如果当前数组不包含任何元素(没有可用的初始值),reduce() 方法将抛出"TypeError"异常 -
<html>
<body>
<script>
const numbers = [];
try {
numbers.reduce((accumulator, currentValue) => accumulator * currentValue);
} catch (error) {
document.write(error);
}
</script>
</body>
</html>
输出
TypeError: Reduce of empty array with no initial value

