forEach()方法对类型化数组的每个元素调用提供的函数。 这个方法的算法和 Array.prototype.forEach()相同。 TypedArray 是这里的 类型化数组类型 之一。
语法
typedarray.forEach(callback[, 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 函数;不像 undefined。
示例
记录类型化数组的内容
下面的代码为数组中的每个元素记录一行日志:
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 | Status | Comment |
|---|---|---|
| ECMAScript 2015 (6th Edition, ECMA-262) %TypedArray%.prototype.forEach |
Standard | 初始定义。 |
| ECMAScript Latest Draft (ECMA-262) %TypedArray%.prototype.forEach |
Draft |
浏览器兼容性
We're converting our compatibility data into a machine-readable JSON format. This compatibility table still uses the old format, because we haven't yet converted the data it contains.
Find out how you can help!
| Feature | Chrome | Firefox (Gecko) | Edge | Internet Explorer | Opera | Safari |
|---|---|---|---|---|---|---|
| Basic support | (Yes) | 38 (38) | (Yes) | 未实现 | ? | 10 |
| Feature | Android | Chrome for Android | Firefox Mobile (Gecko) | IE Mobile | Opera Mobile | Safari Mobile |
|---|---|---|---|---|---|---|
| Basic support | ? | ? | 38.0 (38) | ? | ? | ? |