在 JavaScript 中,Array.reduce() 方法用于操作数组。此方法在数组的每个元素上(从左到右)执行 reducer 函数,并返回一个 'single value' 作为结果。
它接受一个名为 'initialValue' 的可选参数。如果我们不把这个参数传给方法,它会把 arr[0] 值当作初始值。此外,它将对传递的 initialValue 参数执行回调函数。
此方法不会为空数组元素执行 reducer 函数。除此之外,它不会修改原始数组。
注 -如果当前数组为空或不包含任何 initialValue,此方法将引发 'TypeError' 异常。
语法
以下是 JavaScript Array.reduce() 方法的语法 -
reduce(callbackFn(accumulator, currentValue, currentIndex, array), initialValue)
参数
此方法接受两个参数。下面描述相同 -
- callbackFn −这是对数组中的每个元素执行的函数。此函数采用四个参数:
- accumulator -这是 initialValue 或函数之前返回的值。
- currentValue - 当前值 -这是数组中正在处理的当前元素。如果指定了 initialValue,则其值将为 arr[0],否则其值将为 arr[1]。
- currentIndex(可选)−这是数组中正在处理的当前元素的索引。
- array(可选)-这是调用 reduce() 方法的数组。
- initialValue(可选)-首次调用回调函数时 accumulator 参数初始化为的值。
返回值
此方法返回单个值,该值是缩减数组后的结果。
示例 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>
accumulator 从 0 开始,对于数组中的每个元素,它将当前元素添加到accumulator 中。accumulator (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>
accumulator 从 1 开始,对于数组中的每个元素,它将当前元素乘以accumulator 。accumulator 的最终结果 (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