1

New static function

  1. Array.of

    Function type:

    //接收任意数量、任意类型的参数,返回这些参数按照传入顺序组成的数组
    (...args?:any[])=>any[];

Array.of used to create a new array instance variable number of The difference between it and the Array constructor is that when using the new Array method to create an array, if only is passed in as an integer parameter a length of a will be created, with each element All are vacancies (referring to empty , not undefined ), and Array.of will create and return [ a ] .

console.log(Array(3)); //[ <3 empty items> ]
console.log(Array.of(3)); // [ 3 ]

When we need to create an array based on the incoming parameters, if we use the Array constructor, and there is no special treatment when the parameter is only an integer, unexpected situations will occur. This kind of non-logical and detailed problem is often the most difficult for us to realize when repairing.

  1. Array.from

    Function type:

    /**
     * @author: forceddd
     * @desc: 根据传入的一个伪数组或可迭代对象创建一个新的、浅拷贝的数组实例
     * @param {ArrayLike<any>|Iterable<any>} arrayLike 传入的数据源
     * @param {MapFn} mapFn 可选的映射函数,与Array.map用途相同
     * @param {any} thisArg 可选的this对象,映射函数mapFn中的this会指向该参数
     * @return {any[]} 新创建的数组
     */
    (arrayLike:  ArrayLike<any> | Iterable<any>, mapFn?: MapFn, thisArg?: any) => any[];
    
    /**
     * @author: forceddd
     * @desc: 映射回调
     * @param {any} value 数组中的元素
     * @param {number} index 元素的在数组中的下标
     * @return {any} 映射返回的值
     */
    type MapFn = (value: any, index: number) => any;

Array.from is based on a pseudo-array or iterable object create a new , shallow copy of the array instance

Unlike Array.of , Array.of directly uses the parameter as an element in the return value array, while Array.from will generate the return value array based on the incoming parameters:

When an incoming dummy array time, dummy array the length will return the value as an array length , dummy array element will return the value as an element of the array.

//传入了一个伪数组
console.log(Array.from({ 0: '第一项元素', length: 2 }));//[ '第一项元素', undefined ]
// tag属性不能转换成数组下标,被过滤掉了
console.log(Array.from({ 0: '第一项元素', length: 2, tag: '一个字符串key' }));//[ '第一项元素', undefined ]
//传入的是一个普通对象,既不是伪数组,也不是一个iterable对象,返回一个空数组
console.log(Array.from({ 0: '第一项元素', tag: '一个字符串key' }));//[]

When a iterable object parameter is passed in, such as Array , Set etc., the parameters will be iterated and the value obtained by the iteration will be used as the element in the return value array.

console.log(Array.from([1, , 3])); //[ 1, undefined, 3 ]
console.log(Array.from(new Set([1, , 3]))); //[ 1, undefined, 3 ]
//传入了一个映射函数
console.log(Array.from([1, 2, 3], (item) => 2 * item)); //[ 2, 4, 6 ]
const obj = {
    value: 0,
    //自定义   [Symbol.iterator] ,是该对象成为iterable对象,执行得到的迭代器是它自身
    [Symbol.iterator]() {
        return this;
    },
    //value > 3 后,设置迭代状态为true,结束迭代
    next() {
        this.value++;
        return {
            value: this.value,
            done: this.value > 3,
        };
    },
};
//传入一个自定义的iterable
console.log(Array.from(obj));//[ 1, 2, 3 ]

Note that, Array.from no gap ( empty ), if the incoming parameters, the position of the element is gap ( empty ), uses undefined as a result.

When we need to convert a pseudo-array into a real array, in order to use the array's map and other methods-such as dom operation, compared to using [].slice.call(arrayLike) (this method may generate vacancies ( empty ) Element), using Array.from is undoubtedly a more elegant and concise way.

  1. Why should we avoid empty elements in the array?

    In the function of processing array, different functions treat space element in different ways. Some functions ignore space element, such as map function, but some will not ignore it, such as Array.from There are some inexplicable problems.

    If we need to pass a variable count statistics an array of length , which allows us to clearly see vacancy problem element lies.

    When there is a space element:

    const empty = [1, , 3];
    let count1 = 0;
    let count2 = 0;
    empty.map(() => count1++);
    Array.from(empty, () => count2++);
    //由于map函数忽略了空位元素,所以传入的回调只执行了两次,count1的值为2
    console.log({ count1, count2 }); //{ count1: 2, count2: 3 }

When there are no vacant elements:

const normal = [1, undefined, 3];
let count1 = 0;
let count2 = 0;
normal.map(() => count1++);
normal.forEach(() => count2++);

console.log({ count1, count2 }); //{ count1: 3, count2: 3 }

forceddd
271 声望912 粉丝

一名前端爱好者。