ES6 added API: Array

Keywords: Javascript Front-end ECMAScript TypeScript

New prototype method

  1. Array.prototype.copyWithin

    Function type:

    /**
    * @author: forceddd
    * @desc:  Shallow copy the elements in the array from the start position to the end position (excluding the elements at end), and overwrite the array from the target. Finally, the modified array is returned
    * @param {number} target Copy to the starting overwrite position of the array. The default value is 0
    * @param {number} start Start copying the location of the element. The default value is 0
    * @param {number|undefined} end The position where the copied element ends. The default value is the array length
    * @return {any[]} Array after change
    */
    <T>(target?: number, start?: number, end?: number | undefined)=> T[]

    copyWithin copies the elements in the array from the start position to the end position (excluding the element at end), and overwrites the array from the target. Finally, the modified original array is returned.

    //When parameters are not passed in, the default value is used, which is equivalent to [1, 2, 3].copyWithin(0,0,3)
    //First, the part of [0,3) in the array is copied, that is [1,2,3]
    //Then start the overlay from the subscript 0 of the array, and get [1, 2, 3] after the overlay
    console.log([1, 2, 3].copyWithin()); //[ 1, 2, 3 ]
    //Starting from the subscript 1 of the array, the copied part is [1, 2, 3]. Starting from the subscript 1 of the original array, there are only two positions left in the original array, so the result is [1, 1, 2]
    console.log([1, 2, 3].copyWithin(1)); //[ 1, 1, 2 ]

    There are several points to note:

    First, copyWithin will modify the original array and return the modified original array instead of creating a new array.

    const arr = [1, 2, 3];
    const res = arr.copyWithin(1, 0);
    
    console.log(arr === res, arr);//true [ 1, 1, 2 ]

    Second, when target > = arr.length, the copy behavior will not occur, and the original array without any modification will be returned directly.

    const arr = [1, 2, 3];
    const res = arr.copyWithin(6, 2);
    //Returns the original array without any modification
    console.log(arr === res, arr); //true [ 1, 2, 3 ]

    Third, when a negative number is passed in from target, start or end, it means that the value at this time is calculated from the end of the array. If the value passed in is - 1, it represents the position of the penultimate element.

    const arr = [1, 2, 3];
    const res = arr.copyWithin(-2, 2);
    //The copied part from subscript 2 is [3]
    //Starting from - 2, the penultimate element, we get [1, 3, 3]
    console.log(arr === res, arr); //true [ 1, 3, 3 ]
  2. Array.prototype.fill

    Function type:

    /**
    * @author: forceddd
    * @desc: Assign value to the part of the array from the start position to the end (excluding end)
    * @param {any} value The value used to assign values to elements in the array
    * @param {number} start The starting position of the assignment. The default value is 0
    * @param {number} end The end position of the assignment. The default is the length of the array
    * @return {*} The return value is the original array after assignment
    */
    (value?: any, start?: number, end?: number) => any[];

    fill assigns the part of the array from start to end (excluding end) to value, and then returns the array.

    console.log(Array(4).fill()); //[ undefined, undefined, undefined, undefined ]
    console.log(Array(4).fill(0)); //[ 0, 0, 0, 0 ]
    console.log(Array(4).fill(0, 1, 2)); //[ <1 empty item>, 0, <2 empty items> ]

    Like copyWithin, fill returns the original array, and when start or end is a negative number, it is handled in the same way as copyWithin.

    In addition, it can be seen from the code that fill will generate null elements, and if the value value is an object, the reference of the object is used in the assignment. In other words:

    const v = [];
    const arr = Array(4).fill(v);
    console.log(arr[0] === arr[1]); //true
    arr[0].push(1);
    console.log(arr);//[ [ 1 ], [ 1 ], [ 1 ], [ 1 ] ]
  3. Array.prototype.find

    Function type:

    /**
    * @author: forceddd
    * @desc:   Find the first element in the array that causes findFn to return a value of true and return it
    * @param {FindFn} findFn Functions executed on each item of the array
    * @param {any} thisArg this object in the callback function findFn
    * @return {*}
    */
    (findFn: FindFn, thisArg?: any) => any;
    /**
    * @author: forceddd
    * @param {any} item Elements in array
    * @param {number} index The subscript of the current element in the array
    * @param {any} arr Array instance
    * @return {boolean} 
    */
    type FindFn = (item: any, index: number, arr: any[]) => boolean;

    find will return the first element in the array that causes the callback function to return a value of true. If there is no such element, it will return undefined.

    console.log([1, 2, 3].find((v) => v >= 2));//2

    Before ES6, the indexOf method needs strict matching (= = =) to determine whether the element exists. Although the callback function of comparison can be customized by using the some method, it can only return boolean instead of the element itself.

    It should be noted that the execution times of the callback function in find are determined by the index of the array. The range of the index [0, arr.length - 1] will be executed once. It does not care about the value of the current element. Therefore, when the current element is an empty element, the callback function in find will execute the element value as undefined once, which is different from the functions such as map and forEach.

    [1, , 3, 4].find((v) => console.log(v)); //1 undefined 3 4
    [1, , 3, 4].map((v) => console.log(v)); //1 3 4

    In addition, when the callback function in find executes for the first time, its execution times [0, arr.length - 1] It has been determined and will not be changed. This means that if the array arr we want to process is 5 in length, during the execution of the callback function, we modify the ARR to make its length 10, or we delete an element to make its length 4, the callback function will be executed five times. When the element is deleted, the callback function will access it during execution If the element is not found, the execution will continue with undefined instead of the element.

    [1, 2, 3, 4].find((v, i, arr) => {
    //Delete an element
    i === 0 && arr.pop();
    console.log({ v, i });
    }); 
    //{ v: 1, i: 0 }
    //{ v: 2, i: 1 }
    //{ v: 3, i: 2 }
    //{ v: undefined, i: 3 }
  4. Array.prototype.findIndex

    findIndex is basically the same as the find method, except that the return value is different. findIndex returns the subscript of the qualified element. If there is no such element, it will return - 1.

  5. keys,values,entries

    Function type:

    type Keys = () => Iterator<number>;
    type Values = () => Iterator<any>;
    type Entries = () => Iterator<[number, any]>;

    keys, values, and entries do not require any parameters and return an iterator. The difference is that the values in the iterator are array subscripts, array elements, and key value pairs in the form of [I, v] composed of array subscripts and array elements.

    const it = ['a', 'b', 'c'].entries();
    console.log(it.next()); //{ value: [ 0, 'a' ], done: false }
    console.log(it.next()); //{ value: [ 1, 'b' ], done: false }
    console.log(it.next()); //{ value: [ 2, 'c' ], done: false }
    console.log(it.next()); // { value: undefined, done: true }

Posted by matt1 on Mon, 22 Nov 2021 23:01:04 -0800