Js array API details

Array in the usual development process of the use of frequency is very high, familiar with the array of various API usage is necessary, in this data all API to do a detailed introduction

The apis provided by arrays fall into four main categories: constructor methods, change themselves, do not change themselves, and traversal groups

ES2019 new method

  • flat
    • Effect: Array dimension reduction, return a new array, do not change the original array
    • Accept arguments: type Number, default is 1, depending on the argument to lower the dimension level
    Const arr = [2, 3, [4], [5, [6, [7]]]] arr. Flat (1) / / = > [2, 5-tetrafluorobenzoic, [6, [7]]] arr. Flat (2) / / = > [2,3,4,5,6, [7]] arr. Flat (Infinity) / / = >,3,4,5,6,7 [2] the console. The log (arr) / / [2, 3, [4], [5, [6, [7]]]]Copy the code
  • flatMap
    • Function: to unify the data change processing, return a new array, do not change the original array
    • Accept the argument: func
    FlatMap (x => x*2) // [2,4,6] // const arr = [1,2,3] // flatMap(x => x*2) // Inside the type does not restrict arr. FlatMap (x = > [x, x * 2] / /,2,2,4,3,6 [1] arr. FlatMap (x = > [{test:x}]  // [{test: 1}, {test: 2}, {test; 3}] / / returns a {} will all return to undefined arr. FlatMap (x = > {x: x}) / / [, undefined undefined undefined]Copy the code

The Array constructor method

  • of

    Array.of(): Converts the parameters to one of the items in the Array and returns the new Array.

      Array.of(12,'dere', 18) / / = > [12,'derek'18], an Array of (8.0) / / = > [8] Array (8.0) / / = > [8] undefined *Copy the code
  • from

    Array.from(): Converts an array-like object into an Array, returning the new Array without changing the original object

    • Grammar: Array. The from (obj, fn, thisArg)
    • Obj: Object to be converted to an array
    • Fn: method of processing an object
    • ThisArg: this scope
    • Note: The key of the object can only be a number and cannot exceed the length of length
    // The key of the object is a numberlet obj = {0: 'derek', 1:18, 2:'M', length: 3 }
      let arr = Array.from(obj,(val,index)=>{
        val
        index
        return val
      },obj)
      arr // => ['derek', 18.'M'] // The key of the object is not a numeric return undefinedlet obj = {name: 'derek', 1:18, 0:'M', length: 3 }
      let arr = Array.from(obj,(val,index)=>{
        val
        index
        return val
      },obj)
      arr // => ['M',18,undefined]
    Copy the code
  • isArray

    Array.isarray (): checks whether a variable is an Array: array.isarray (arr)

      letArr = [1, 2, 3]let a = Array.isArray(arr)
      a// => true
    Copy the code

Change your API

  • push

    Push (): Pushes an element to the end of the target array and returns the element’s latest length

      let arr = ['a'.'b'.'c']
      let len = arr.push('d')
      console.log(arr,len) // => ['a'.'b'.'c'.'d'4]Copy the code
  • unshift

    Unshift (): Presses an element at the top of the target array and returns the length of the element

      let arr = ['a'.'b'.'c']
      let len = arr.unshift('d')
      console.log(arr,len) // => ['d'.'a'.'b'.'c'4]Copy the code
  • pop

    Pop (): Pushes out an element at the end of the target array and returns the pushed element

      let arr = ['a'.'b'.'c'.'d']
      let a = arr.pop()
      console.log(arr,a) // => ['a'.'b'.'c']  'd'
    Copy the code
  • shift

    Shift (): Presses an element at the top of the target array and returns the pushed element

      let arr = ['a'.'b'.'c'.'d']
      let a = arr.shift()
      console.log(arr,a) // => ['b'.'c'.'d']  'a'
    Copy the code
  • reverse

    Reverse (): Reverses the order of the array so that the first becomes the last and the last becomes the first, returning the current array

      let arr = ['a'.'b'.'c'.'d']
      let arr2 = arr.reverse()
      console.log(arr) // => ['d'.'c'.'b'.'a']
      console.log(arr2) // => ['d'.'c'.'b'.'a']
      console.log(arr2===arr) // => true
    Copy the code
  • sort

    Sort (): Quicksort the array order and returns the current array

    • A: Default sort: without passing arguments (arr.sort()), array elements are sorted by their Unicode points converted to strings
    • B: Custom sort: If you pass in the desired sort method (arr.sort((a,b) => a-b)), the sorting will be in descending order
    // Sort an array of numbersletAaa =,4,52,64,234,6,8 [3]let arr = aaa.sort()
      letArr1 = aaa. Sort (a, b) = > (a - b). The console log (arr) / / = >,3,4,52,6,64,8 [234] the console. The log (arr1) / / = >,4,6,8,52,64,234 [3] -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- / / for quick sort element is an array of objectslet arr = [{name: 'derek',age: 18 },{ name: 'tom', age: 28 },{ name: 'lily', age: 18 },{ name:  'lucy', age: 22 }]
      let aa = arr.sort((a,b)=> a.age-b.age)
      console.log(aa) // => [{name:'derek',age:18},{ name: 'lily', age: 18 },{ name:  'lucy', age: 22 },{ name: 'tom', age: 28 }]
    Copy the code

    Note:

    • When using sort() to sort an array, insert sort is used when the array has less than 10 elements
    • When there are more than 10 elements in the array, we use quicksort, which is unstable and can make mistakes
    • Solution: array. Sort ((a, b) = > a – b | | array. The indexof (a) – array. Indexof (b))

    In ES2019, the sort method has been optimized and the internal sort method has been changed from quickSort to TimSort, which solves the problem of sorting instability

  • splice

    Splice (): insert, delete, or replace an array, return an array containing the deleted elements: arr.splice(start,count,item1,item2) start: Arr. Length count: the number of elements to delete, if greater than the length of the array. 0, if there is a third element, it is the insert element item1, item2: the element added to the array

    // Delete elementslet arr = ['tom'.'derek'.'lily'.'lucy']
      letA = arr.splice(0,2) console.log(arr) // => ['lily'.'lucy']
      console.log(a)  // => ['tom'.'derek'] // Replace elementslet arr = ['tom'.'derek'.'lily'.'lucy']
      letB = arr. Splice (1, 2,'david')
      console.log(arr)  //=> ['david'.'lily'.'lucy']
      console.log(b)   // => ['tom'.'derek'] // Insert elementslet arr = ['tom'.'derek'.'lily'.'lucy']
      letC = arr. Splice (2, 0,'nina')
      console.log(arr)  // => ['tom'.'derek'.'nina'.'lily'.'lucy']
      console.log(c)   // => []
    Copy the code

    Note: When the data is larger than the array length at the start of the delete, the default is to push elements into the end of the array

      let arr = ['tom'.'derek'.'lily'.'lucy']
      letB = arr. Splice (5, 2,'david')
      console.log(arr)  //=> ['tom'.'derek'.'lily'.'lucy'.'david']
      console.log(b)   // => []
    Copy the code
  • copyWithin

    CopyWithin (): An element replacement, which returns the changed array when both the replaced element and the replaced element are in the array

    • Grammar: array. Copywithin (target, start, end)
    • Target: The starting index of the element to be replaced
    • Start: The start index of the replacement element, which can be negative
    • End: Replaces the end index of the element. The default value is array.length, which can be negative
      letArr = [1, 2, 3, 4, 5]letResult = arr.copywithin (0,2,3) console.log(result === arr,arr) // =>true(3, 2, 3, 4, 5]letArr = [1, 2, 3, 4, 5] arr. CopyWithin (1, 3) the console. The log (arr) / / = >,4,5,4,5 [1]letArr = [1, 2, 3, 4, 5] arr. CopyWithin (1, 2, 1) the console. The log (arr) / / = >,4,3,4,5 [1]Copy the code
  • fill

    Fill (): Replaces the element in the specified range of positions in the array with the specified value, returning the changed array

    • Grammar: array. The fill (val, start, end)
    • Val: Specifies the replacement value
    • Start: the start index to be replaced, which can be negative
    • End: The end index to be replaced, which can be negative and does not contain the array length
      letArr = [1, 2, 3, 4, 5] const a = arr. The fill,1,3 (6) the console. The log (a = = = arr, arr) / / = >true,6,6,4,5 [1]letArr = [1, 2, 3, 4, 5] const a = arr. The fill (6, 3, 1) the console. The log (arr) / / = >,2,6,6,5 [1]Copy the code

Do not change their API

  • concat

    Concat (): Merges the array or elements passed in to form a new array

    • Grammar: arr. Concat (val1, val2…).
    • Note: Arguments can be arrays when only one latitude is lowered for merge
      letArr = [1, 2, 3]letAaa = arr. Concat (1, 2, [three, four, five], [6]) to the console. The log (aaa, arr) / / = >,2,3,4,5,6,7 [1] [1, 2, 3]letBBB = arr. Concat (1, 2, 3, 4 and 6]]) to the console. The log (BBB) / / = > [1, 2, 3, 4 and 6]]Copy the code
  • join

    Join (): Concatenates the elements of an array into a string with a custom link character and returns

    • Grammar: array. Join (val)
    • Val: Link between elements, default ‘,’
      letArr = [1, 2, 3, 4] arr. The join () / / = > 1, 2, 3, 4 arr. Join (The '-') / / = > 1-2-3-4Copy the code
  • slice

    Slice (): Copies part of the array into a new array and returns the array

    • Grammar: array. Slice (start, end)
    • Start: indicates the start index of the copied array. The value can be negative (-2 => array.length-2)
    • End: Copy the end index of the array, not including the element, not passing the default to the last element
    • Note: Without passing any arguments, you can make a shallow copy of slice().
      letArr = [6] arr. Slice (1, 4) / / = > [4] 2 arr. Slice (2) / / = >,4,5,6 [3] arr. Slice (3, 5) / / = > (4 and 6)Copy the code
  • toString

    ToString (): Returns an array as a string, equivalent to join ()

    • Grammar: array. The toString ()
    • Note: The toString method is automatically called when array and string elements are + concatenated
      let array = ['a'.'b'.'c'.'d']
      array.toString()  // => a,b,c,d
      array+'e' // => a,b,c,de
    Copy the code
  • toLocalString

    ToLocalString (): A variation like toString() that consists of the toLocaleString() return values for each element in the array joined (separated by commas) by the call to join()

    • Grammar: array. ToLocalString ()
    • Note: Each element in the array calls its own toLocalString method
      • Object: the Object. The prototype. ToLocaleString ()
      • Number: Number. The prototype. ToLocaleString ()
      • Date: the Date. The prototype. ToLocaleString ()
      let arr = [{name: 'derek'}, 22,'M',new Date()]
      arr.toLocalString() // => '[object,object],22,M,2019/3/5 1:06:23PM'
    Copy the code
  • indexOf

    IndexOf (): Finds the first index position of an element in an array, and returns -1 if there is none

    • Grammar: array indexOf (el, start)
    • El: the element to be searched for
    • Start: indicates the subscript position to start the search
    • Note:
      • The default value is 0
      • Start > array.length, -1 is returned
      • Start < 0, starting at array.length + start
      • Start + array.length < 0
      letArr =,3,4,5,7,9,0,7,45,6,8 [1]let a =arr.indexOf(1) // => 0
      letB = arr.indexof (1,3) // => -1let c = arr.indexOf(7,-5) // => 7
      let d = arr.indexOf(7, -10) // => 4
    Copy the code
  • lastIndexOf

    LastIndexOf (): the lastIndexOf an element in an array, -1 if none is present

    • Grammar: array lastIndexOf (el, start)
    • El: the element to be searched for
    • Start: indicates the subscript position to start the search
    • Example: Refer to indexOf
  • includes

    Includes (): Checks whether an element exists in the array. Returns true if it does, false if it does not

    • Grammar: array. Includes (el, start)
    • El: The target element to find
    • Start: indicates the index to start the search. The default value is 0
      var array = [1, 2, NaN];
      array.includes(1) // true
      array.includes(NaN) // true
      array.includes(2,-4) // true
    Copy the code

API for array traversal

  • forEach

    ForEach (): Specifies that each element in the array executes the function passed in once, returning undefinded

    • Grammar: arr. ForEach (fn, thisArg)
    • Fn: method to execute for each element, taking three arguments fn(el,index,array)
    • El: the element being processed
    • Index: The index of the element being processed
    • Array: indicates the array itself
    • ThisArg: this object inside the fn function
    • Note: the fn function is executed once for each item in the array. Items that have been deleted, added, or never assigned are skipped (except items with undefined value).
      letArr = [1, 2, 3, 4, 5]leta = arr.forEach((el,index)=> { arr[index] = el * index }) console.log(a) // => undefined console.log(arr) // => ,2,6,12,20 [0]Copy the code
  • map

    Map (): Processes each function in the array using the function passed in, and forms each return value into a new array and returns it

    • Grammar: arr. The map (fn, thisArg)
    • Fn: method executed for each array element
    • El: the element being processed
    • Index: The index of the element being processed
    • Array: indicates the array itself
    • ThisArg: fn function within thisArg, generally not passed
      letArr = [1, 2, 3, 4]letResult = arr.map((item,index) => item * index) console.log(result) // => [0,2,6,12] console.log(arr) // => [1,2,3,4]Copy the code
  • filter

    Filter (): Calls the passed function for each element in the array, forms a new array with the elements that meet the criteria and returns them

    • Grammar: arr. Filter (fn)
    • Fn: a conditional function that determines whether an element satisfies the target element
      let,2,3,4,5,6,7 arr = [1] arr. Filter (item = > item > 3) / / = > [4, 7] arr. Filter (item = > item > 8) / / = > [] arr. Filter (item = > items % 2 === 0) // => [2,4,6,8]Copy the code
  • reduce

    Reduce (): The method receives a method as an accumulator, and each value in the array (from left to right) is merged to a single value

    • Grammar: arr. Reduce (fn, initVal)
    • Fn: represents the function executed on each element of the array, taking four arguments
      • PreviousValue The value returned by the last call to the callback, or the initial value provided
      • Value Specifies the value of the element currently being processed in the array
      • Index Indicates the index of the current element in the array
      • Array Array itself
      • InitVal: adds the initial value
      • Note: when fn executes for the first time
        • If initialValue exists, the first previousValue = initialValue, item = the first value in the array;
        • If initialValue does not exist, then previousVaule = the first value in the array and item = the second value in the array. If the array is empty at this point, TypeError is raised.
        • If the array has only one element, but the array is empty, fn is not executed and the unique value of the array is returned
    // For summationletArr = [1,2,3,4,5] arr.reduce((prev,value)=>value * prev,0) // => 120 // used for other applicationsletArr = [1, 2, 3, 4, 5]let result = arr.reduce = ((prev,value,index) => {
        value > 2 ? prev.push(value)
        returnPrev},[]) console.log(result) // => [3,4,5]Copy the code
  • reduceRight

    ReduceRight (): The method accepts a method as an accumulator, and each value in the array (from right to left) begins to merge and ends up as a value

    • Grammar: arr. Reduce (fn, initVal)
    • Fn: represents the function executed on each element of the array, taking four arguments
    • For details, see the reduce function
  • some

    Some (): compares all elements in the array, returns true if any of them meet the criteria, and terminates the loop, returns false if all of them do not meet the criteria

    • Grammar: arr. Some (fn)
    • Fn: method executed for each element
      letArr = [6] arr. Some (item = > item = 3) / / = >true
      arr.some(item => item > 8)  // => false
    Copy the code
  • every

    Every (): compares all elements in the array, returns true if all elements are satisfied, and false if one element is not satisfied

    • Grammar: arr. Every (fn)
    • Fn: method executed for each element
      letArr = [1, 2, 3, 4, 5] arr. Every (item = > item > 0) / / = >true
      arr.every(item => item > 2)  // => false
    Copy the code
  • find

    Find (): Returns the first element in the array that meets the criteria (if any), or undefined if none

    • Grammar: array. The find (fn, thisArg)
    • Fn: find conditional function
    • ThisArg: fn function runs this object inside, generally not passed
      letArr = [1,2,3,4,5,6] arr.find(item => item>3) // => 4 Arr. find(item => item < 1) // => undefinedCopy the code
  • findIndex

    FindIndex (): Returns the index (if any) of the first element in the array that meets the criteria, or -1 if none

    • Grammar: array. FindIndex (fn, thisArg)
    • Fn: conditional function
    • ThisArg: fn function runs this object inside, generally not passed
      letArr = [1,2,3,4,5] arr.findIndex(item => item > 3) // => 3 Arr.findIndex (item => item < 0) // => -1Copy the code
  • keys

    Keys (): returns an iterator to the array index

    • Grammar: array keys ()
      let arr = ['a'.'b'.'c']
      let aa = arr.keys()
      console.log(aa.next())  // => Object {value: 0, done: false}
      console.log(aa.next())  // => Object {value: 1, done: false}
      console.log(aa.next())  // => Object {value: 2, done: false}
      console.log(aa.next())  // => Object {value: undefined, done: true} // Note: keys for objectslet obj = {name: 'derek',age:18}
      Object.keys(obj)  // => ['name'.'age']
    Copy the code
  • values

    Values (): Iterator that returns an array value

    • Grammar: array values ()
      let arr = ['a'.'b'.'c']
      let aa = arr.values()
      console.log(aa.next())  // => Object {value: 'a'.done: false}
      console.log(aa.next())  // => Object {value: 'b'.done: false}
      console.log(aa.next())  // => Object {value: 'c'.done: false}
      console.log(aa.next())  // => Object {value: undefined, done: true} // Note: values for objectslet obj = {name: 'derek',age:18}
      Object.values(obj)  // => ['derek'18],Copy the code
  • entries

    Entries (): Returns an array iterator object containing the key-value pairs for each index in the array

    • Grammar: array. Entries ()
      let arr = ['derek'.'tom']
      let aa = arr.entries()
      console.log(aa.next())  // => {value:[0:'derek],done: false} console.log(aa.next()) // => {value:[1:'tom],done: false}
      console.log(aa.next())  // => {value:undefined,done: true} // Object with entrieslet obj = {name: 'derek',age:18}
      console.log(Object.entries(obj)) // => [[name:'derek'],[age:18]]
    Copy the code