TypedArray.prototype.map()

TypedArray 实例的 map() 方法创建一个新的类型化数组,其中填充了对调用类型化数组中的每个元素调用所提供函数的结果。该方法与 Array.prototype.map() 的算法相同。

¥The map() method of TypedArray instances creates a new typed array populated with the results of calling a provided function on every element in the calling typed array. This method has the same algorithm as Array.prototype.map().

Try it

语法

¥Syntax

js
map(callbackFn)
map(callbackFn, thisArg)

参数

¥Parameters

callbackFn

对类型化数组中的每个元素执行的函数。它的返回值作为单个元素添加到新的类型化数组中。使用以下参数调用该函数:

element

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

index

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

array

调用了类型化数组 map()

thisArg Optional

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

返回值

¥Return value

一个新的类型化数组,其中每个元素都是回调函数的结果。

¥A new typed array with each element being the result of the callback function.

描述

¥Description

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

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

示例

¥Examples

将类型化数组映射到平方根类型化数组

¥Mapping a typed array to a typed array of square roots

以下代码采用一个类型化数组并创建一个新的类型化数组,其中包含第一个类型化数组中数字的平方根。

¥The following code takes a typed array and creates a new typed array containing the square roots of the numbers in the first typed array.

js
const numbers = new Uint8Array([1, 4, 9]);
const roots = numbers.map(Math.sqrt);
// roots is now: Uint8Array [1, 2, 3],
// numbers is still Uint8Array [1, 4, 9]

使用包含参数的函数映射类型化的数字数组

¥Mapping a typed array of numbers using a function containing an argument

以下代码显示了当需要一个参数的函数与 map() 一起使用时,map() 如何工作。当 map() 循环原始类型化数组时,参数将自动分配给类型化数组的每个元素。

¥The following code shows how map() works when a function requiring one argument is used with it. The argument will automatically be assigned to each element of the typed array as map() loops through the original typed array.

js
const numbers = new Uint8Array([1, 4, 9]);
const doubles = numbers.map((num) => num * 2);
// doubles is now Uint8Array [2, 8, 18]
// numbers is still Uint8Array [1, 4, 9]

规范

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

¥Specifications

浏览器兼容性

BCD tables only load in the browser

¥Browser compatibility

也可以看看