TypedArray.prototype.forEach()

Baseline Widely available

This feature is well established and works across many devices and browser versions. It’s been available across browsers since March 2016.

forEach() 方法对类型化数组的每个元素调用提供的函数。这个方法的算法和 Array.prototype.forEach() 相同。TypedArray 是这里的类型化数组类型之一。

语法

js
forEach(callbackFn)
forEach(callbackFn, thisArg)

参数

callback

产生新的类型化数组的元素的函数,接受三个函数:

currentValue

类型化数组中要处理的当前元素

index

类型化数组中要处理的当前元素的下标

array

forEach()在其上调用的类型化数组

thisArg

可选,执行callback时作为this的值。

返回值

描述

forEach方法对类型化数组中的元素按升序调用提供的 callback函数。它不会对删除或者省略的下标调用,但是会对存在并且值为undefined的元素调用。

callback三个参数调用:

  • the 元素的值
  • the 元素下标
  • the 被遍历的类型化数组

如果将 thisArg 参数提供给 forEach,它会在调用时传递给 callback,作为它的 this 值。否则,会传递 undefined 作为它的 this 值。callback最终观测到的 this 值由用于决定函数可见的 this 值的一般规则来决定。

forEach处理的元素范围在callback调用之前就确定了。在 forEach调用之后添加到数组的元素不会由 callback访问。如果类型化数组的现有元素被改变,或被删除,它们传给callback的值是forEach 访问它们时候的值。已删除的元素不会被访问。

forEach()对每个数组元素执行一次callback 函数;不像 every()some(),它始终返回 undefined

示例

记录类型化数组的内容

下面的代码为数组中的每个元素记录一行日志:

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

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

规范

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

浏览器兼容性

BCD tables only load in the browser

参见