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 September 2016.
TypedArray.from() 静态方法从类似数组或可迭代对象创建新的 类型数组。该方法与 Array.from() 几乎相同。
¥The TypedArray.from() static method creates a new
typed array
from an array-like or iterable object. This method is nearly the same as
Array.from().
Try it
语法
¥Syntax
TypedArray.from(arrayLike, mapFn)
TypedArray.from(arrayLike, mapFn, thisArg)
其中 TypedArray 是以下之一:
¥Where TypedArray is one of:
参数
返回值
描述
¥Description
详细信息请参见 Array.from()。
¥See Array.from() for more details.
Array.from() 和 TypedArray.from() 之间有一些细微的区别(注意:下面提到的 this 值是调用 TypedArray.from() 时使用的 this 值,而不是用于调用 mapFn 的 thisArg 参数):
¥There are some subtle distinctions between Array.from() and TypedArray.from() (note: the this value mentioned below is the this value that TypedArray.from() was called with, not the thisArg argument used to invoke mapFn):
- 如果
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)
来自字符串
与箭头函数和映射一起使用
生成数字序列
在非 TypedArray 构造函数上调用 from()
¥Calling from() on non-TypedArray constructors
from() 的 this 值必须是返回 TypedArray 实例的构造函数。
¥The this value of from() must be a constructor that returns a TypedArray instance.
function NotArray(len) {
console.log("NotArray called with length", len);
}
Int8Array.from.call({}, []); // TypeError: #<Object> is not a constructor
Int8Array.from.call(NotArray, []);
// NotArray called with length 0
// TypeError: Method %TypedArray%.from called on incompatible receiver #<NotArray>
function NotArray2(len) {
console.log("NotArray2 called with length", len);
return new Uint8Array(len);
}
console.log(Int8Array.from.call(NotArray2, [1, 2, 3]));
// NotArray2 called with length 3
// Uint8Array(3) [ 1, 2, 3 ]
规范
| Specification |
|---|
| ECMAScript Language Specification # sec-%typedarray%.from |
浏览器兼容性
BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.