ES6 added API: array (II)

Time:2022-5-16

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 is copied to the initial coverage position of the array, and the default value is 0
    *@ param {number} start starts copying the position of the element. The default value is 0
    *@ param {number | undefined} end ends the position of the copied element. The default value is the array length
    *@ return {any []} changed array
    */
    <T>(target?: number, start?: number, end?: number | undefined)=> T[]

    copyWithinFrom the arraystartPosition start toendLocation(nocontainendThe element at the end of theShallow replication, and fromtargetStart overwriting the array at. Finally, the modifiedprimaryArray return.

    //When no parameter is 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,copyWithinWill modify the original array and returnModified original arrayInstead 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, whentarget>=arr.lengthWhen,can’tWhen copying occurs, the original array without any modification is 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, whentargetstartperhapsendafferentnegativeWhen, it represents the currentCalculate from the end of the array, if the value passed in is-1, on behalf ofLast but oneThe location of the 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 start to end (excluding end)
    *@ param {any} value is the value used to assign values to elements in the array
    *@ param {number} start the starting position of the assignment, which is 0 by default
    *The end position of @ param {number} end 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[];

    fillRemove array fromstartPosition start toendEnd (excludingend)All parts of are assignedvalue, and then return 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> ]

    fillandcopyWithinThe same goes for the returnOriginal arrayAnd whenstartperhapsendbynegativeWhen, it is also andcopyWithinThe same treatment.

    In addition, it can also be seen from the code,fillWill producevacancyElement, and ifvalueValue isobject, the assignment usesObject reference。 let me put it another way:

    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 makes the return value of findfn true and return it
    *Function executed on each item of @ param {findfn} findfn array
    *@ param {any} this object in findfn of thisarg callback function
    * @return {*}
    */
    (findFn: FindFn, thisArg?: any) => any;
    /**
    * @author: forceddd
    *Elements in the @ param {any} item array
    *@ param {number} index the index of the current element in the array
    *@ param {any} arr array instance
    * @return {boolean} 
    */
    type FindFn = (item: any, index: number, arr: any[]) => boolean;

    findWill return the array so that the return value of the callback function istrueoffirstElement, ifNo,Such elements will returnundefined

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

    Before ES6, useindexOfMethods need to be strictly matched(===)To determine whether an element exists, usesomeMethod can customize the callback function of comparison, but it can only returnbooleanInstead of getting the element itself.

    It should be noted that,findOf callback function inNumber of executionsIs based on an arraysubscriptDetermined, subscript[ 0 , arr.length - 1 ]It doesn’t care about the value of the current element, so the current element isvacancyElement,findThe callback function inElement valueAsundefinedExecute once, this andmapforEachEqual functions are different.

    [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, whenfindThe number of times a callback function in is executed for the first time[ 0 , arr.length - 1 ]It’s already determined, andIt won’t change again。 That means, suppose we’re dealing with an arrayarrCount Reg5, during the execution of the callback function, we modifiedarr, making its length10Or we delete an element so that its length becomes4, the callback function will execute5Times. When an element isdeleteIf the callback function cannot access the element during execution, it willundefinedContinue execution instead of this 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

    findIndexAndfindThe methods are basically the same, except for the return value,findIndexThe returned is the subscript of the qualified element. If there is no such element, it will be returned-1

  5. keys,values,entries

    Function type:

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

    keysvaluesentriesNo parameters are required and an iterator is returned. The difference is that the values in the iterator are composed of the index of the array, the elements of the array, the index of the array and the elements of the array[ i , v ]Key value pairs in the form.

    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 }

Recommended Today

Monitoring etcd outside the cluster in kubesphere

Author: Zhang Yanying (old z), operation and maintenance architect of Shandong Branch of telecom system integration company, cloud native enthusiast, currently focusing on cloud native operation and maintenance. 1. Introduction This article comes from @ jam, a small partner in kubesphere’s open source community 8 group, who mentioned that there is no data for ectd […]