TypedArray .from() method creates a new typed array from an array-like or iterable object. This method is nearly the same as Array.from() .

The source for this interactive example is stored in a GitHub repository. If you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.

句法

TypedArray.from(source[, mapFn[, thisArg]])
					

Where TypedArray is one of:

参数

source

An array-like or iterable object to convert to a typed array.

mapFn 可选

Map function to call on every element of the typed array.

thisArg 可选
Value to use as this when executing mapFn .

返回值

A new TypedArray 实例。

描述

TypedArray .from() lets you create typed arrays from:

  • array-like objects (objects with a length property and indexed elements); or
  • iterable objects (objects where you can get its elements, such as Map and Set ).

TypedArray .from() has the optional parameter mapFn , which allows you to execute a map() function on each element of the typed array (or subclass object) that is being created. This means that the following are equivalent:

  • TypedArray .from( obj , mapFn , thisArg )
  • TypedArray .from(Array.prototype.map.call( obj , mapFn , thisArg )) .

length 特性为 from() method is 1 .

Differences from Array.from()

Some subtle distinctions between Array.from() and TypedArray .from() :

  • thisArg value passed to TypedArray.from() is not a constructor, TypedArray.from() will throw a TypeError , where Array.from() defaults to creating a new Array .
  • TypedArray.from() 使用 [[Put]] where Array.from() 使用 [[DefineProperty]] . Hence, when working with Proxy objects, it calls handler.set to create new elements rather than handler.defineProperty() .
  • When the source parameter is an iterator, the TypedArray.from() first collects all the values from the iterator, then creates an instance of thisArg using the count, then sets the values on the instance. Array.from() sets each value as it receives them from the iterator, then sets its length at the end.
  • When Array.from() gets an array-like which isn't an iterator, it respects holes. TypedArray.from() will ensure the result is dense.

Polyfill

You can partially work around this by inserting the following code at the beginning of your scripts, allowing use of much of the functionality of from() in implementations that do not natively support it.

if (!Int8Array.__proto__.from) {
    (function () {
        Int8Array.__proto__.from = function (obj, func, thisObj) {
            var typedArrayClass = Int8Array.__proto__;
            if(typeof this !== 'function') {
                throw new TypeError('# is not a constructor');
            }
            if (this.__proto__ !== typedArrayClass) {
                throw new TypeError('this is not a typed array.');
            }
            func = func || function (elem) {
                    return elem;
                };
            if (typeof func !== 'function') {
                throw new TypeError('specified argument is not a function');
            }
            obj = Object(obj);
            if (!obj['length']) {
                return new this(0);
            }
            var copy_data = [];
            for(var i = 0; i < obj.length; i++) {
                copy_data.push(obj[i]);
            }
            copy_data = copy_data.map(func, thisObj);
            var typed_array = new this(copy_data.length);
            for(var i = 0; i < typed_array.length; i++) {
                typed_array[i] = copy_data[i];
            }
            return typed_array;
        }
    })();
}
							

范例

From an iterable object (Set)

const s = new Set([1, 2, 3]);
Uint8Array.from(s);
// Uint8Array [ 1, 2, 3 ]
							

From a string

Int16Array.from('123');
// Int16Array [ 1, 2, 3 ]
							

Use with arrow function and map

Using an arrow function as the map function to manipulate the elements

Float32Array.from([1, 2, 3], x => x + x);
// Float32Array [ 2, 4, 6 ]
							

Generate a sequence of numbers

Uint8Array.from({length: 5}, (v, k) => k);
// Uint8Array [ 0, 1, 2, 3, 4 ]
							

规范

规范
ECMAScript (ECMA-262)
The definition of '%TypedArray%.from' in that specification.

浏览器兼容性

The compatibility table on this page is generated from structured data. If you'd like to contribute to the data, please check out https://github.com/mdn/browser-compat-data and send us a pull request. 更新 GitHub 上的兼容性数据
Desktop Mobile Server
Chrome Edge Firefox Internet Explorer Opera Safari Android webview Chrome for Android Firefox for Android Opera for Android Safari on iOS Samsung Internet Node.js
from Chrome 45 Edge 14 Firefox 38 IE No Opera No Safari 10 WebView Android No Chrome Android No Firefox Android 38 Opera Android No Safari iOS 10 Samsung Internet Android No nodejs 4.0.0

图例

完整支持

完整支持

不支持

不支持

另请参阅

元数据

  • 最后修改:
  1. 标准内置对象
  2. TypedArray
  3. 特性
    1. TypedArray.BYTES_PER_ELEMENT
    2. TypedArray.name
    3. TypedArray.prototype.buffer
    4. TypedArray.prototype.byteLength
    5. TypedArray.prototype.byteOffset
    6. TypedArray.prototype.length
    7. get TypedArray[@@species]
  4. 方法
    1. TypedArray.from()
    2. TypedArray.of()
    3. TypedArray.prototype.copyWithin()
    4. TypedArray.prototype.entries()
    5. TypedArray.prototype.every()
    6. TypedArray.prototype.fill()
    7. TypedArray.prototype.filter()
    8. TypedArray.prototype.find()
    9. TypedArray.prototype.findIndex()
    10. TypedArray.prototype.forEach()
    11. TypedArray.prototype.includes()
    12. TypedArray.prototype.indexOf()
    13. TypedArray.prototype.join()
    14. TypedArray.prototype.keys()
    15. TypedArray.prototype.lastIndexOf()
    16. TypedArray.prototype.map()
    17. TypedArray.prototype.reduce()
    18. TypedArray.prototype.reduceRight()
    19. TypedArray.prototype.reverse()
    20. TypedArray.prototype.set()
    21. TypedArray.prototype.slice()
    22. TypedArray.prototype.some()
    23. TypedArray.prototype.sort()
    24. TypedArray.prototype.subarray()
    25. TypedArray.prototype.toLocaleString()
    26. TypedArray.prototype.toString()
    27. TypedArray.prototype.values()
    28. TypedArray.prototype[@@iterator]()
  5. 相关页面:
  6. Int8Array
  7. Uint8Array
  8. Uint8ClampedArray
  9. Int16Array
  10. Uint16Array
  11. Int32Array
  12. Uint32Array
  13. Float32Array
  14. Float64Array
  15. BigInt64Array
  16. BigUint64Array
  17. 继承:
  18. Function
  19. 特性
    1. Function.arguments
    2. Function.caller
    3. Function.displayName
    4. Function.length
    5. Function.name
  20. 方法
    1. Function.prototype.apply()
    2. Function.prototype.bind()
    3. Function.prototype.call()
    4. Function.prototype.toSource()
    5. Function.prototype.toString()
  21. Object
  22. 特性
    1. Object.prototype.__proto__
    2. Object.prototype.constructor
  23. 方法
    1. Object.prototype.__defineGetter__()
    2. Object.prototype.__defineSetter__()
    3. Object.prototype.__lookupGetter__()
    4. Object.prototype.__lookupSetter__()
    5. Object.prototype.hasOwnProperty()
    6. Object.prototype.isPrototypeOf()
    7. Object.prototype.propertyIsEnumerable()
    8. Object.prototype.toLocaleString()
    9. Object.prototype.toSource()
    10. Object.prototype.toString()
    11. Object.prototype.valueOf()
    12. Object.setPrototypeOf()