map()方法对类型化数组的每个元素调用提供的函数,并使用结果来创建新的类型化数组。 这个方法的算法和 Array.prototype.map()相同。 TypedArray 是这里的 类型化数组类型 之一。
语法
typedarray.map(callback[, thisArg])
参数
-
callback -
产生新的类型化数组的元素的函数,接受三个函数:
-
currentValue - 类型化数组中要处理的当前元素
-
index - 类型化数组中要处理的当前元素的下标
-
array -
map在其上调用的类型化数组
-
-
thisArg -
可选,执行
callback时作为this的值。
返回值
新的类型化数组
描述
map方法对类型化数组中的元素调用提供的 callback函数,按照顺序,并且会从结果构造新的类型化数组。 callback 只对拥有值的类型化数组下标调用。它不会对未定义的,被删除的或者没有赋值的下标调用。
callback 以三个参数调用: 元素的值,元素下标,和被遍历的类型化数组。
如果将thisArg参数提供给map,它会在调用时传递给callback,作为它的 this值。否则,会传递undefined 作为它的this 值。 callback最终观测到的this值由 用于决定函数可见的this值的一般规则来决定。
map 不改变在其上调用的类型化数组(虽然如果调用了callback可能会这样做)。
由 map处理的元素范围在callback调用之前就确定了。 在 map调用之后添加到数组的元素不会由 callback访问。 如果类型化数组的现有元素被改变,或被删除,它们传给callback的值是map 访问它们时候的值。已删除的元素不会被访问。
示例
将类型数组映射被平方根的类型数组
下面的代码接受一个类型数组,并创建一个新的类型数组,含有第一个类型数组中元素的平方根。
var numbers = new Uint8Array([1, 4, 9]); var roots = numbers.map(Math.sqrt); // roots is now: Uint8Array [1, 2, 3], // numbers is still Uint8Array [1, 4, 9]
使用含有参数的函数来映射类型数组
下面的代码展示了,当使用需要一个参数的函数时,map的工作方式。在map遍历原始数组的过程中,参数会自动赋值为类型化数组的每个元素。
var numbers = new Uint8Array([1, 4, 9]);
var doubles = numbers.map(function(num) {
return num * 2;
});
// doubles is now Uint8Array [2, 8, 18]
// numbers is still Uint8Array [1, 4, 9]
规范
| Specification | Status | Comment |
|---|---|---|
| ECMAScript 2015 (6th Edition, ECMA-262) TypedArray.prototype.map |
Standard | 原始定义。 |
| ECMAScript Latest Draft (ECMA-262) TypedArray.prototype.map |
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) | Internet Explorer | Opera | Safari |
|---|---|---|---|---|---|
| Basic support | (Yes) | 38 (38) | 未实现 | 未实现 | 未实现 |
| Feature | Android | Chrome for Android | Firefox Mobile (Gecko) | IE Mobile | Opera Mobile | Safari Mobile |
|---|---|---|---|---|---|---|
| Basic support | 未实现 | 未实现 | 38.0 (38) | 未实现 | 未实现 | 未实现 |