JavaScript - TypedArray reduce() 方法
JavaScript TypedArray reduce() 方法对类型化数组的每个元素执行用户提供的"reducer"回调函数。它返回一个单个值,该值是对整个类型化数组执行回调函数的结果。
它接受一个名为 'initialValue' 的可选参数。如果我们不将此参数传递给该方法,它将把 arr[0] 的值视为初始值。此外,它还会对传递的 initialValue 参数执行回调函数。
注意 − 如果当前 TypedArray 为空或不包含任何初始值,此方法将抛出 'TypeError' 异常。
语法
以下是 JavaScript TypedArray reduce() 方法的语法 −
reduce(callbackFn, initialValue)
参数
此方法接受两个名为"callbackFn"和"initialValue"的参数,如下所述 −
callbackFn − 用户提供的函数,用于对 TypedArray 的每个元素执行。
此 callbackFn 函数也接受四个参数,分别是'accumulator'、'currentValue'、'currentIndex' 和 'array'。以下是每个参数的描述:
accumulator − 此参数表示先前迭代产生的累积值。它从初始值(显式提供或数组的第一个元素)开始,并在每次迭代时更新。
currentValue − 类型数组中当前元素的值。如果指定了 initialValue,则其值为 arr[0];否则,其值为 arr[1]。
currentIndex − currentValue 在类型化数组中的索引位置。
array − 调用 reduce() 方法的类型化数组。
initialValue − 首次调用回调函数时,累加器参数初始化的值。
返回值
此方法返回一个值,该值是在整个类型化数组上执行"reducer"回调函数后的结果。
示例
示例 1
类型化数组中所有元素的乘积。
在以下示例中,我们使用 JavaScript TypedArray 的 reduce() 方法,对类型数组 [1, 2, 3, 4, 5] 中的每个元素执行用户提供的函数 multi()。multi() 函数会将当前类型数组中的所有元素相乘。
<html>
<head>
<title>JavaScript TypedArray reduce() Method</title>
</head>
<body>
<script>
//function
function multi(accumulator, currentValue){
return accumulator * currentValue;
}
const T_array = new Uint16Array([1, 2, 3, 4, 5]);
document.write("Typed array: ", T_array);
//使用 reduce() 方法
document.write("<br>The product of typed array elements: ", T_array.reduce(multi));
</script>
</body>
</html>
输出
上述程序返回类型数组元素的乘积 120。
Typed array: 1,2,3,4,5 The product of typed array elements: 120
示例 2
如果我们将 initialValue 参数传递给此方法,reduce() 方法也会对其执行用户提供的回调函数,并返回单个值作为结果。
在下面的示例中,我们使用 JavaScript TypedArray reduce() 方法对类型数组 [10, 20, 30, 40, 50] 的每个元素(包括传递的 initialValue 参数值 10)执行用户提供的名为 sum() 的回调函数。sum() 函数会累加当前类型数组中所有元素的总和。
<html>
<head>
<title>JavaScript TypedArray reduce() Method</title>
</head>
<body>
<script>
const T_array = new Uint16Array([10, 20, 30, 40, 50]);
document.write("Typed array: ", T_array);
const initialValue = 10;
document.write("<br>Initial value: ", initialValue);
let sum = T_array.reduce(function(accumulator, currentValue){
return accumulator + currentValue;
}, initialValue);
document.write("<br>The sum of typed array elements(including initial value): ", sum);
</script>
</body>
</html>
输出
执行上述程序后,它将返回类型数组中所有元素(包括初始值)的总和 -
Typed array: 10,20,30,40,50 Initial value: 10 The sum of typed array elements(including initial value): 160
示例 3
如果当前类型数组不包含任何元素(没有可用的初始值),reduce() 方法将抛出 "TypeError" 异常。
在下面给出的示例中,我们使用 JavaScript TypedArray reduce() 方法对这个空类型数组 ([]) 的每个元素执行用户提供的名为"ArrowFunction"的 Reducer 回调函数。
<html>
<head>
<title>JavaScript TypedArray reduce() Method</title>
</head>
<body>
<script>
const T_array = new Uint16Array([]);//empty typed array
document.write("Length of the typed array: ", T_array.length);
//使用 reduce 方法
try {
T_array.reduce((a, b)=> a + b);
} catch (error) {
document.write("<br>", error);
}
</script>
</body>
</html>
输出
上述程序执行后,将抛出"TypeError"异常。
Length of the typed array: 0 TypeError: Reduce of empty array with no initial value

