A RetroSearch Logo

Home - News ( United States | United Kingdom | Italy | Germany ) - Football scores

Search Query:

Showing content from https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/TypedArray/from below:

TypedArray.from() - JavaScript | MDN

TypedArray.from()

Baseline Widely available

TypedArray.from() 静态方法从类数组对象或可迭代对象创建一个新的类型化数组。此方法与 Array.from() 几乎相同。

尝试一下
const uint16 = Int16Array.from("12345");

console.log(uint16);
// Expected output: Int16Array [1, 2, 3, 4, 5]
语法 参数
arrayLike

要转换为类型化数组的可迭代对象或类数组对象。

mapFn 可选

对类型化数组的每个元素调用的函数。如果提供了该函数,数组中要添加的每个值首先会传递给该函数,然后将 mapFn 的返回值添加到类型化数组中。该函数使用以下参数调用:

element

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

index

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

thisArg 可选

执行 mapFn 时用作 this 的值。

返回值

一个新的 TypedArray 实例。

描述

详情请参见 Array.from()。

Array.from() 和 TypedArray.from() 之间存在一些微妙的区别(注意:下面提到的 this 值是指调用 TypedArray.from() 时的 this 值,而不是用于调用 mapFn 的 thisArg 参数):

示例 从可迭代对象(Set)
const s = new Set([1, 2, 3]);
Uint8Array.from(s);
// Uint8Array [ 1, 2, 3 ]
从字符串
Int16Array.from("123");
// Int16Array [ 1, 2, 3 ]
与箭头函数和 map 一起使用

使用箭头函数作为 map 函数来操作元素

Float32Array.from([1, 2, 3], (x) => x + x);
// Float32Array [ 2, 4, 6 ]
生成一个数字序列
Uint8Array.from({ length: 5 }, (v, k) => k);
// Uint8Array [ 0, 1, 2, 3, 4 ]
在非 TypedArray 构造函数上调用 from()

from() 的 this 值必须是一个返回 TypedArray 实例的构造函数。

function NotArray(len) {
  console.log("调用 NotArray 时的长度", len);
}

Int8Array.from.call({}, []); // TypeError: #<Object> is not a constructor
Int8Array.from.call(NotArray, []);
// 调用 NotArray 时的长度 0
// TypeError: Method %TypedArray%.from called on incompatible receiver #<NotArray>
function NotArray2(len) {
  console.log("调用 NotArray2 时的长度", len);
  return new Uint8Array(len);
}
console.log(Int8Array.from.call(NotArray2, [1, 2, 3]));
// 调用 NotArray2 时的长度 3
// Uint8Array(3) [ 1, 2, 3 ]
规范 浏览器兼容性 参见

RetroSearch is an open source project built by @garambo | Open a GitHub Issue

Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo

HTML: 3.2 | Encoding: UTF-8 | Version: 0.7.4