TypedArray.prototype.forEach()

TypedArray 实例的 forEach() 方法为每个类型化数组元素执行一次提供的函数。该方法与 Array.prototype.forEach() 的算法相同。

¥The forEach() method of TypedArray instances executes a provided function once for each typed array element. This method has the same algorithm as Array.prototype.forEach().

Try it

语法

¥Syntax

js
forEach(callbackFn)
forEach(callbackFn, thisArg)

参数

¥Parameters

callbackFn

对类型化数组中的每个元素执行的函数。它的返回值被丢弃。使用以下参数调用该函数:

element

类型化数组中正在处理的当前元素。

index

类型化数组中当前正在处理的元素的索引。

array

调用了类型化数组 forEach()

thisArg Optional

执行 callbackFn 时用作 this 的值。参见 迭代法

返回值

¥Return value

无 (undefined)。

¥None (undefined).

描述

¥Description

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

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

示例

¥Examples

记录类型化数组的内容

¥Logging the contents of a typed array

以下代码为类型化数组中的每个元素记录一行:

¥The following code logs a line for each element in a typed array:

js
function logArrayElements(element, index, array) {
  console.log(`a[${index}] = ${element}`);
}

new Uint8Array([0, 1, 2, 3]).forEach(logArrayElements);
// Logs:
// a[0] = 0
// a[1] = 1
// a[2] = 2
// a[3] = 3

规范

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

¥Specifications

浏览器兼容性

BCD tables only load in the browser

¥Browser compatibility

也可以看看