ES6 added API: Array

Keywords: Javascript Front-end ECMAScript

New static function

  1. Array.of

    Function type:

    //Receive any number and type of parameters, and return an array of these parameters in the order they are passed in
    (...args?:any[])=>any[];

    Array.of is used to create a new Array instance with a variable number of parameters. The difference between it and creating arrays through the array constructor is that when creating arrays using the new Array method, if only an integer parameter a is passed in, an array with a length of a will be created, and each element is empty (meaning empty, not undefined), while 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 passed in parameters, if the Array constructor is used, and there is no special treatment for the case where the parameter is only an integer, unexpected situations will occur. This is not a logical and detailed problem. When repairing, it is often the most difficult for us to realize.

  2. Array.from

    Function type:

    /**
     * @author: forceddd
     * @desc: Create a new, shallow copy of the array instance based on an incoming pseudo array or iteratable object
     * @param {ArrayLike<any>|Iterable<any>} arrayLike Incoming data source
     * @param {MapFn} mapFn Optional mapping function, the same purpose as Array.map
     * @param {any} thisArg Optional this object. This in the mapping function mapFn will point to this parameter
     * @return {any[]} Newly created array
     */
    (arrayLike:  ArrayLike<any> | Iterable<any>, mapFn?: MapFn, thisArg?: any) => any[];
    
    /**
     * @author: forceddd
     * @desc: Mapping callback
     * @param {any} value Elements in array
     * @param {number} index The subscript of the element in the array
     * @return {any} Value returned by mapping
     */
    type MapFn = (value: any, index: number) => any;

    Array.from is a Pseudo array Or create a new, shallow copy of the array instance using the iteratable object.

    Unlike Array.of, Array.of directly takes parameters as elements in the return value array, while Array.from generates the return value array according to the passed parameters:

    When incoming Pseudo array When, Pseudo array The length of will be used as the length of the return value array, Pseudo array The element of is used as the element of the return value array.

    //A pseudo array was passed in
    console.log(Array.from({ 0: 'First element', length: 2 }));//['first element', undefined]
    // The tag attribute cannot be converted to an array subscript and is filtered out
    console.log(Array.from({ 0: 'First element', length: 2, tag: 'A string key' }));//['first element', undefined]
    //What is passed in is an ordinary object, neither a pseudo array nor an iterable object, and returns an empty array
    console.log(Array.from({ 0: 'First element', tag: 'A string key' }));//[]

    When an iterable object parameter is passed in, such as Array, Set, etc., the parameter 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 ]
    //A mapping function was passed in
    console.log(Array.from([1, 2, 3], (item) => 2 * item)); //[ 2, 4, 6 ]
    const obj = {
        value: 0,
        //Custom [Symbol.iterator] makes the object an iterable object, and the iterator obtained by execution is itself
        [Symbol.iterator]() {
            return this;
        },
        //After value > 3, set the iteration status to true and end the iteration
        next() {
            this.value++;
            return {
                value: this.value,
                done: this.value > 3,
            };
        },
    };
    //Pass in a custom iterable
    console.log(Array.from(obj));//[ 1, 2, 3 ]

    It should be noted that Array.from will not generate empty bits. If the element at this position is empty in the passed in parameters, undefined will be used as the result.

    When we need to put one Pseudo array When converting to a real array to use the map and other methods of the array -- such as dom operation, using Array.from is undoubtedly a more elegant and concise way than using []. slice.call(arrayLike) (this method may produce empty elements).

  3. Why avoid empty elements in arrays?

    In the functions dealing with arrays, different functions treat empty elements differently. Some functions ignore empty elements, such as the map function, while others do not, such as Array.from, which is likely to cause some inexplicable problems.

    If we need to count the length of an array through the variable count, we can clearly see the problem of empty elements.

    When there are empty elements:

    const empty = [1, , 3];
    let count1 = 0;
    let count2 = 0;
    empty.map(() => count1++);
    Array.from(empty, () => count2++);
    //Because the map function ignores empty elements, the incoming callback is executed only twice, and the value of count1 is 2
    console.log({ count1, count2 }); //{ count1: 2, count2: 3 }

    When no empty element exists:

    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 }

Posted by fishdishdesign on Mon, 22 Nov 2021 11:12:25 -0800