Summary of JavaScript common array methods

Time:2022-8-3
  • Add / remove elements

    • push()

      • Add element at the end of array
      let arr = ['javascript', 'css'];
      
      alert( arr.push('html') );// 3
      
      alert( arr );// javascript, css, html
    • pop()

      • Remove and return the last element of the array
      let arr = ['javascript', 'css'];
      
      alert( arr.pop() );// css
      
      alert( arr );// javascript
    • unshift()

      • Add an element at the beginning of the array
      let arr = ['is', 'head'];
      
      alert( arr.unshift('here') );// 3
      
      alert( arr );// here, is, head
    • shift()

      • Remove and return the first element of the array
      let arr = ['here', 'is', 'head'];
      
      alert( arr.shift() );// here
      
      alert( arr );// is, head
    • splice()

      • You can add, delete and insert elements to the array
      arr.splice(start[, deleteCount, elem1, ..., elemN])
      • startIs the index value to start this operation,deleteCountIs the number of deleted,elemReplace or add elements for, for example:
      let arr = ["hello", "world", "web", "html"]
      
      alert( arr.splice(1, 2, "javascript","css") );//hello,javascript,css,html   
      //Delete 2 elements from index 1, and replace "JavaScript" and "CSS" to the original position
      • Note:spliceMethod returns an array containing the deleted elements, rather than a new array after deleting the elements
    • slice()

      • From indexstartTo indexendCreate a new array (with indexstart, but without indexend
      arr.slice([start], [end])
      let arr = ['h', 't', 'm', 'l'];
      
      alert( arr.slice( 1, 3) );// t,m
      alert( arr.slice(-4,-1) );// h,t,m
      alert( arr.slice(1) );// t,m,l
      alert( arr.slice() );//  h,t,m,l  ; Equivalent to generating a copy of the array
    • concat()

      • Adding parameters (arrays or values) to the end of the original array and returning this new array will not affect the original array
      let arr = [1, 2];
      alert( arr.concat(3, 4) );//1,2,3,4
      alert( arr.concat([3, 4], [5, 6], 7, 8) );//1,2,3,4,5,6,7,8
      alert( arr );//1,2
      • If the parameter is an object, it is added as a whole by default:
      let arr = [1, 2];
      
      let obj = {
      	0: "html",
      	1: "css"
      };
      
      alert( arr.concat(obj) );//1,2,[object Object]
      • You can addSymbol.isConcatSpreadableProperty to solve this problem:
      let arr = [1, 2];
      
      let obj = {
      	0: "html",
      	1: "css",
      	[Symbol.isConcatSpreadable]: true
      };
      
      alert( arr.concat(obj) );//1,2,html,css
  • Search elements

    • indexOf / lastIndexOf / includes

      • indexOf( item, from )

        • From indexfromStart searchitem, if found, return the index, otherwise return-1
      • lastIndexOf( item, from )

        • Same as above, but search from the end
      • includes( item, from )

        • From indexfromStart searchitem, return if foundtrue, otherwise returnfalse
      let arr = [1, 0, false];
      
      alert( arr.indexOf(0) ); // 1
      alert( arr.indexOf(false) ); // 2
      alert( arr.indexOf(null) ); // -1
      
      alert( arr.includes(1) ); // true
      • Note: these three methods useStrictly equal (= =), finditemNo type conversion will be performed on the item; If you want to know whether the array contains an element and you don’t know its index value, you should give priority to using itincludes
    • find / findIndex

      • find()

        • Return the array that meets the providedcallbackFunctionalFirst elementValue of, otherwise returnundefined
        • callbackReceive up to three parameters(item, index, array), ifcallbackMedium returntrueThen stop the iteration and returnitem, otherwise no search is found, returnundefined
        arr.find(callback[, thisArg])
        • Commonly used in object arrays
        let users = [
          {id: 1001, name: "Mike"},
          {id: 1002, name: "Pete"},
          {id: 1003, name: "Mary"}
        ];
        
        let user = users.find(item => item.name == "Mary");
        
        alert(user.id); // 1003
      • findIndex()

        • Andfind()Basically the same, the difference isfindIndex()The index value is returned, and it will be returned when the search fails-1
    • filter()

      • Filter array, usage andfind()Same, but it returnsAll qualifiedAn array of elements of

        let users = [
          {id: 1001, name: "Mike"},
          {id: 1002, name: "Pete"},
          {id: 1003, name: "Jack"},
          {id: 1004, name: "Mary"}
        ];
        
        let user = users.filter(item => item.id > 1001);
        
        alert( user.length ); //3
        user.forEach( item => alert(item.name) );// Pete, Jack, Mary
  • Traversal element

    • forEach()

      • Call a function for each element of the array,No return value
      let arr = ['hello', 'javascript'];
      
      arr.forEach(alert);// Call alert for each element
      • Match arrow function:
      let arr = ['hello', 'javascript'];
      
      arr.forEach((item, index, array) => {
          Alert (`${item} is the value with index ${index} in ${array});
      });
  • Convert array

    • map()

      • Call a function for each element in the array and return the result array (equivalent toforEach()
      let arr = ['hello', 'javascript'];
      
      let length = arr.map( item => item.length );// Convert the element itself to the length of the element
      alert( arr );//hello, javascript
      alert( length );//5, 10
    • sort()

      • sort(fn)Can be performed for an arrayin situSort (directly modify the original array itself),fnThe sorting function provides the basis for sorting

      • fn(a, b)The principle of providing sorting criteria:

        • Iffn(a, b)Less than 0, then a will be arranged before B
        • Iffn(a, b)Equal to 0, the relative position of a and B remains unchanged
        • Iffn(a, b)Greater than 0, B will be arranged before a
      • sort( (a, b) => a - b )(ascending)sort( (a, b) => b - a )(descending):

        let arr = [ 18, 2, 13 ];
        
        arr.sort( (a, b) => a - b );
        alert(arr);  //  Ascending order; 2, 13, 18
        
        arr.sort( (a, b) => b - a );
        alert(arr);  //  Descending order; 18, 13, 2
      • To sort words with more letters accurately,fnSorting function should matchstr.localeCompare()method:

        let arr = ["javascript", "css", "html", "Österreich"];
        
        arr.sort( (a, b) => a.localeCompare(b) );
        
        alert( arr );// css, html, javascript, Österreich
    • reverse()

      • Invert array, invert elements in array

        let arr = [1, 2, 3];
        
        alert( arr.reverse() );//3, 2, 1
    • split / join

      • split()

        • str.split(separator)Can becharacter stringDivide into one according to the specified conditionsarrayReturn after

          • separator(separator) can be string, regular expression, array, etc
          let str = "This , is javascript";
          
          //No delimiter, return an array with the whole string as the element
          alert( str.split() );// This , is javascript
          
          //The separator is an empty string. In case of character segmentation, an array of letters with each character as an element is returned
          alert( str.split('') );// T,h,i,s, ,,, ,i,s, ,j,a,v,a,s,c,r,i,p,t
          
          //The separator is a space. In case of space segmentation, an array with multiple strings as elements is returned
          alert( str.split(' ') );// This,,,is,javascript
          
          //The separator is a comma. In case of comma division, an array with multiple strings as elements is returned
          alert( str.split(',') );// This , is javascript
      • join()

        • arr.join(separator)Andsplit()Instead, it willarrayElements inseparatorConnect into onecharacter stringReturn after

          let arr = ['This', 'is', 'javascript'];
          
          //There is no delimiter, and elements are separated by "," between them
          alert( arr.join() );// This,is,javascript
          
          //The separator is an empty string, and there is no character separation between elements
          alert( arr.join('') );// Thisisjavascript
          
          //The separator is a space, and the elements are separated by a space
          alert( arr.join(' ') );// This is javascript
          
          //The separator is' - ', and the elements are separated by "-"
          alert( arr.join('-') );// This-is-javascript
    • reduce()

      arr.reduce(callback(accumulator, currentValue[, index[, array]])[, initialValue])
      • Execute one for each element in the arraycallbackFunction and summarize its results into a single return value

      • callbackReceive 4 parameters:

        • acc(accumulator is the cumulative value returned in the last callback, orinitialValue)
        • cur(array elements being processed)
        • index(index of the array element being processed, if anyinitialValue, then 0, otherwise start from 1)
        • array(callreduce()Array of)
      • initialValue(ascallbackThe value of the first parameter in the array, if none, the value of the first element in the array is used)

        let arr = [1, 2, 3, 4, 5, 6];
        
        let addAll = arr.reduce( (sum, current) => (sum + current), 0);// 1+2+3+..+6
        
        alert( addAll );// 21
      • reduceRight()Andreduce()The function is the same, only traversing from right to left

      • Note: initialvalue should always be set, otherwise an error will be reported when the called array is an empty array

Recommended Today

Spring cloud 2021.0.1 removes Netflix components such as hystrix and zuul

1. PrefaceOn December 22, 2020, the official spring blog announced that spring cloud 2020.0.0 was officially released. 2020.0.0 is the first spring cloud release to use the new version number naming scheme. Before that, spring cloud used the naming method of London underground station to name a large version (train version). If it is not […]