此页面由社区从英文翻译而来。了解更多并加入 MDN Web Docs 社区。
TypedArray.from()
Baseline Widely available
This feature is well established and works across many devices and browser versions. It’s been available across browsers since 2016年9月.
TypedArray.from() 静态方法从类数组对象或可迭代对象创建一个新的类型化数组。此方法与Array.from() 几乎相同。
In this article
尝试一下
const uint16 = Int16Array.from("12345");console.log(uint16);// Expected output: Int16Array [1, 2, 3, 4, 5]语法
js
TypedArray.from(arrayLike, mapFn)TypedArray.from(arrayLike, mapFn, thisArg)其中TypedArray 是以下类型之一:
参数
返回值
一个新的TypedArray 实例。
描述
详情请参见Array.from()。
Array.from() 和TypedArray.from() 之间存在一些微妙的区别(注意:下面提到的this 值是指调用TypedArray.from() 时的this 值,而不是用于调用mapFn 的thisArg 参数):
- 如果
TypedArray.from()的this值不是构造函数,TypedArray.from()会抛出TypeError,而Array.from()默认会创建一个新的Array。 - 由
this构造的对象必须是一个TypedArray实例,而Array.from()允许其this值构造为任何对象。 - 当
source参数是一个迭代器时,TypedArray.from()首先从迭代器中收集所有值,然后使用计数创建一个this实例,最后将值设置到该实例上。Array.from()在接收到来自迭代器的每个值时设置其值,然后在最后设置其length。 TypedArray.from()使用[[Set]],而Array.from()使用[[DefineOwnProperty]]。因此,在处理Proxy对象时,它调用handler.set()来创建新元素,而不是调用handler.defineProperty()。- 当
Array.from()接收到一个不是迭代器的类数组时,它会保留空洞。TypedArray.from()将确保结果是密集的。
示例
>从可迭代对象(Set)
js
const s = new Set([1, 2, 3]);Uint8Array.from(s);// Uint8Array [ 1, 2, 3 ]从字符串
js
Int16Array.from("123");// Int16Array [ 1, 2, 3 ]与箭头函数和 map 一起使用
使用箭头函数作为 map 函数来操作元素
js
Float32Array.from([1, 2, 3], (x) => x + x);// Float32Array [ 2, 4, 6 ]生成一个数字序列
js
Uint8Array.from({ length: 5 }, (v, k) => k);// Uint8Array [ 0, 1, 2, 3, 4 ]在非 TypedArray 构造函数上调用 from()
from() 的this 值必须是一个返回TypedArray 实例的构造函数。
js
function NotArray(len) { console.log("调用 NotArray 时的长度", len);}Int8Array.from.call({}, []); // TypeError: #<Object> is not a constructorInt8Array.from.call(NotArray, []);// 调用 NotArray 时的长度 0// TypeError: Method %TypedArray%.from called on incompatible receiver #<NotArray>js
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 ]规范
| Specification |
|---|
| ECMAScript® 2026 Language Specification> # sec-%typedarray%.from> |