TypedArray.prototype.reduce()

TypedArray 实例的 reduce() 方法按顺序对类型化数组的每个元素执行用户提供的 "reducer" 回调函数,并传入前一个元素计算的返回值。在类型化数组的所有元素上运行缩减程序的最终结果是单个值。该方法与 Array.prototype.reduce() 的算法相同。

¥The reduce() method of TypedArray instances executes a user-supplied "reducer" callback function on each element of the typed array, in order, passing in the return value from the calculation on the preceding element. The final result of running the reducer across all elements of the typed array is a single value. This method has the same algorithm as Array.prototype.reduce().

Try it

语法

¥Syntax

js
reduce(callbackFn)
reduce(callbackFn, initialValue)

参数

¥Parameters

callbackFn

对类型化数组中的每个元素执行的函数。其返回值在下次调用 callbackFn 时成为 accumulator 参数的值。对于最后一次调用,返回值变为 reduce() 的返回值。使用以下参数调用该函数:

accumulator

上次调用 callbackFn 所产生的值。第一次调用时,如果指定了后者,则其值为 initialValue;否则其值为 array[0]

currentValue

当前元素的值。第一次调用时,如果指定了 initialValue,则其值为 array[0];否则其值为 array[1]

currentIndex

类型化数组中 currentValue 的索引位置。第一次调用时,如果指定了 initialValue,则其值为 0,否则为 1

array

调用了类型化数组 reduce()

initialValue Optional

第一次调用回调时 accumulator 被初始化的值。如果指定了 initialValue,则 callbackFn 将从类型化数组中的第一个值 currentValue 开始执行。如果未指定 initialValue,则 accumulator 会初始化为类型化数组中的第一个值,而 callbackFn 会以类型化数组中的第二个值 currentValue 开始执行。在这种情况下,如果类型化数组为空(因此没有第一个值作为 accumulator 返回),则会引发错误。

返回值

¥Return value

在整个类型化数组上运行 "reducer" 回调函数直至完成所产生的值。

¥The value that results from running the "reducer" callback function to completion over the entire typed array.

例外情况

¥Exceptions

TypeError

如果类型化数组不包含元素并且未提供 initialValue,则抛出该错误。

描述

¥Description

详细信息请参见 Array.prototype.reduce()。此方法不是通用的,只能在类型化数组实例上调用。

¥See Array.prototype.reduce() for more details. This method is not generic and can only be called on typed array instances.

示例

¥Examples

对数组中的所有值求和

¥Sum up all values within an array

js
const total = new Uint8Array([0, 1, 2, 3]).reduce((a, b) => a + b);
// total === 6

规范

Specification
ECMAScript Language Specification
# sec-%typedarray%.prototype.reduce

¥Specifications

浏览器兼容性

BCD tables only load in the browser

¥Browser compatibility

也可以看看