JS from()

🌙
手机阅读
本文目录结构

**_TypedArray_.from()** 方法 从一个类数组或者可迭代对象中创建一个新类型数组。 这个方法和 Array.from()类似。

语法

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

where TypedArray is one of:

Int8Array
Uint8Array
Uint8ClampedArray
Int16Array
Uint16Array
Int32Array
Uint32Array
Float32Array
Float64Array

参数

source

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

mapFn

可选参数。如果指定了该参数,则最后生成的类型数组会经过该函数的加工处理后再返回。

thisArg

可选参数。执行 mapFn 函数时 this 的值。

返回值

一个新的 TypedArray 实例。

 描述

_TypedArray_.from() 允许你从下面两者来创建数组:

  • 类数组对象(拥有一个 length 属性和若干索引属性的任意对象)
  • 可迭代对象(你可以从它身上迭代出若干个元素的对象,比如有 MapSet 等)。

_TypedArray_.from() 方法有一个可选参数 mapFn, 让你可以在最后生成的类型数组上再执行一次 map 方法后再返回。也就是说 _TypedArray_.from(obj, mapFn, thisArg) 和_TypedArray_.from(Array.prototype.map.call(obj, mapFn, thisArg)) 是等价的。

 from()length 属性为1.

Array.from() 和 _TypedArray_.from()之间有一些微妙的区别:

  • 如果 |this| 的值传递给 _TypedArray_.from 不是一个构造器, _TypedArray_.from 将抛出{jsxref(“TypeError”)}}, 而 Array.from 默认将创建一个 Array.
  • _TypedArray_.from 使用[Put] 而 rray.from 使用[DefineProperty]]. 因此, 当和 Proxy 对象一起时, 它调用 handler.set 创建一个新的元素而非 handler.defineProperty.
  • 当 from 获得一个迭代器时, _TypedArray_ 一开始收集迭代器中的所有值, 此时创建一个 |this| 的实例用于计数, 然后在实例中设置值。 Array.from 设置每个从迭代器其中获取的值,最后设置它的长度。
  • 当 Array.from 获得一个不可迭代的类数组时, it respects holes, 而 _TypedArray_.from 将确保结果是 dense.

示例

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


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


// 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 ]

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;
        }
    })();
}

Specifications

Specification Status Comment
[ECMAScript 2015 (6th Edition, ECMA-262)
%TypedArray%.from](https://www.ecma-international.org/ecma-262/6.0/#sec-%typedarray%.from) Standard Initial definition.
[ECMAScript Latest Draft (ECMA-262)
%TypedArray%.from](https://tc39.es/ecma262/#sec-%typedarray%.from) Draft  

Browser compatibility

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.

Update compatibility data on GitHub

Desktop Mobile Server
Chrome Edge Firefox
from Chrome Full support 45 Edge Full support 14 Firefox Full support 38

Legend

Full support  

Full support

No support  

No support

See also

AXIHE / 精选资源

浏览全部教程

面试题

学习网站

前端培训
自己甄别

前端书籍

关于朱安邦

我叫 朱安邦,阿西河的站长,在杭州。

以前是一名平面设计师,后来开始接接触前端开发,主要研究前端技术中的JS方向。

业余时间我喜欢分享和交流自己的技术,欢迎大家关注我的 Bilibili

关注我: Github / 知乎

于2021年离开前端领域,目前重心放在研究区块链上面了

我叫朱安邦,阿西河的站长

目前在杭州从事区块链周边的开发工作,机械专业,以前从事平面设计工作。

2014年底脱产在老家自学6个月的前端技术,自学期间几乎从未出过家门,最终找到了满意的前端工作。更多>

于2021年离开前端领域,目前从事区块链方面工作了