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
语法
参数
返回值
描述
¥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.
示例
将类型化数组映射到平方根类型化数组
¥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.
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.
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 |
浏览器兼容性
BCD tables only load in the browser