Common Methods for Arrays

1. Common methods of arrays

  1. push

  • Syntax: array.push( data)

  • Function: add data to the end of the array

  • Return value: After appending data, the latest length of the array (length)

var arr = [1, 2, 3]
console.log(arr.push(500))   //The return value is the array length: 4 
console.log(arr)             //Print the original array as: [1,2,3,500]
  1. pop

  • Syntax: Array.pop()

  • Function: delete the last data after the array

  • Return value: the deleted data

var arr = [1, 2, 3]
console.log(arr.pop())      //The return value is the deleted data: 3  
console.log(arr)            //Print the original array as: [1,2,]

3.unshift

  • Syntax: array.unshift( data)

  • Function: add data to the front of the array

  • Return value: the latest length of the array after adding data to the front

var arr = [1, 2, 3]
console.log(arr.unshift(500))       //The return value is the array length: 4  
 console.log(arr)                    //Print the original array as: [500, 1, 2, 3]
  1. shift

  • Syntax: array.shift()

  • Function: delete the first data of the array

  • Return value: the deleted data

var arr = [1, 2, 3]
console.log(arr.shift())       //The return value is the deleted data: 1  
console.log(arr)               //Print the original array as: [2, 3]
  1. reverse

  • Syntax: array.reverse()

  • Function: reverse the array

  • Return value: new array after inversion

var arr = [1, 2, 3]
console.log(arr.reverse())              //The reversed array is: [3,2,1]

6.sort

  • Syntax 1: Array.sort()

  • Syntax 2: Array.sort(function(a,b){return(a-b)}) (arrange from small to large)

  • Syntax 3: Array.sort(function(a,b){return(b-a)}) (arranged from large to small)

  • Function: sort

  • Return value: sorted new array

var arr1 = [1,100,100001,1002,300,100000002]
console.log(arr1.sort())     //[1,100,300,1002,100001,100000002]
//Syntax 1, sort from small to large according to the number of digits (if there are strings, pure numbers participate in the comparison, not pure numbers, put them at the end of the array in order)

var arr2 = [1,200,300,5,80,123]
var res2 = arr2.sort(function(a,b){return(a - b)})
console.log(arr2) 
//Syntax 2: Arrange from small to large, the printed array is: [1, 5, 80, 123, 200, 300]


var arr3 = [1,200,300,5,80,123]
var res3 = arr3.sort(function(a,b){return(b - a)})
console.log(arr3) 
//Syntax 3: Arrange from large to small, the printed array is: [300, 200, 123, 80, 5, 1]

7.splice

  • Syntax 1: Array.splice( start index, how many)

  • Function: intercept part of the content of the array

  • Return value: an array composed of the intercepted part of the content

  • Syntax 2: Array.splice( start index, how many, inserted data 1, inserted data 2...)

  • Function: Intercept part of the content of the array and insert new data

  • Return value: an array composed of the intercepted part of the content

Note: The above 7 methods will change the original array

8.slice

  • Syntax: array.slice( start index, end index)

  • Function: intercept part of the content of the array

  • Return value: a new array composed of the intercepted part of the content

  • parameter:

  • Before the package, not after the package

  • Do not write the start index, the default is 0

  • Do not write the end index, the end index is equivalent to writing the length of the array

  • The parameter supports writing negative numbers, indicating the penultimate number (that is, length + negative integer)

var arr = [1,2,3,4,5,6,7,8,9]

           0,1,2,3,4,5,6,7,8
console.log(arr.slice(3,6))  //The return value is: [4,5,6]

console.log(arr.slice() )         
//The start index is not written, the default is 0, and the end index is not written, which is equivalent to arr.length, then it will be printed when printing

console.log(arr.slice(3,-2))  //4,5,6,7
//It is equivalent to starting from the position of index 3, and the end position is equivalent to length+negative number. That is, the position of index 7, that is, arr.slice(3,7)

Interview question: What is the difference between splice and slice?

Reply:

  • The parameters are different:

  • The function of splice is to intercept part of the array and decide whether to insert data; in the writing of parameters, the parameter can have multiple data, the first parameter represents the starting index position, and the second parameter represents the amount of data to be intercepted, then The following parameters indicate the data to be added, there can be none or more.

  • The role of slice is to intercept part of the data fragments; in the writing of parameters, the first parameter is the position of the start index, the default value is 0, and the second parameter is the position of the end index, the default value is the length of the array; the parameter takes " The principle of "wrapping the front and not the back", that is, only the number of the start index position is reserved, and the number of the end index position is not reserved; the parameter can also be a negative number, indicating the number from the bottom.

  • spice will change the original array, but slice will not change the original array.

9.concat

  • Syntax: original array.contact( array 1, array 2,...., data 1, data 2....)

  • Function: splicing data, splicing the content in parentheses such as array data into the original array

  • Return value: spliced ​​array

var arr = [1,2,3]
var res = arr.concat([100,200,400],[0,1000],'abc','100000')
console.log(res)
//Return value: [1, 2, 3, 100, 200, 400, 0, 1000, 'abc', '100000']

10.join

  • Syntax: array.join('connector')

  • Function: Use the "connector" to connect each data in the array into a string (do not write the connector, the default is a comma)

  • Return value: concatenated string

var arr = [1,2,3]
var str = arr.join('-')
console.log(str)        //The return value is: 1-2-3 copy code

11.indexOf

  • Syntax 1: array.indexOf( data to check)

  • Function: Check the index of the first occurrence of the data in the array from left to right

  • Return value: If the data is found, it will return the subscript of the first occurrence of the data; if it is not found, it will directly return -1

  • Syntax 2: array.indexOf( data to check, position to start index)

  • Function: At the starting index position, in order from left to right, check the index position where the data first appears in the array

  • Return value: If the data is found, it will return the subscript of the first occurrence of the data; if it is not found, it will directly return -1

var arr = [1,2,6,2,0,3,4,5,6,7]

           0,1,2,3,4,5,6,7,8,9
var num = arr.indexOf(6)       //If the value of the start index is not written, the default value is 0
var num1 = arr.indexOf(6,5)    //The data to be checked at this time is the number 6 means to search for the index position of 6 from left to right from the position of index 5
console.log(num)               //The return value is: 2
console.log(num1)              //The printed value is: 8

12.lastIndexOf

  • Syntax 1: array.lastIndexOf( data to check)

  • Function: Check the index of the first occurrence of the data in the array in order from right to left (from back to front)

  • Syntax 2: array.lastIndexOf( data to check, start index)

  • Function: At the starting index position, in order from right to left (back to front), check the index of the first occurrence of the data in the array

  • Return value: If the data is found, it will return the subscript of the first occurrence of the data; if it is not found, it will directly return -1

var arr = [1,2,6,2,0,3,4,5,6,7]
           0,1,2,3,4,5,6,7,8,9
var num = arr.lastIndexOf(6)       //If the value of the start index is not written, the default value is 0
var num1 = arr.lastIndexOf(6,5)    //Indicates to search for the index position of 6 from right to left starting from the position of index 5
console.log(num)               //The return value is: 8
console.log(num1)              //The printed value is: 2

Second, the common method of traversing the array

  1. forEach

  • Syntax: Array.forEach(function(item,index,origin){ })

  • item: the value of each item of the array

  • index: the subscript corresponding to each item of the array

  • origin: the original array (just understand, generally not)

  • Function: traverse the array

  • Return value: never return value (undefined)

var arr = [1,2,3,4,5,6,7,8,9]
arr.forEach(function(item,index,origin)
    console.log(item,index)
      }) 
  1. map

  • Syntax: Array.map(function(item,index,origin){})

  • Role: mapping array

  • Return value: returns an array with the same length as the original array, but the internal data can be processed by mapping (that is, written in the form of return in the function)

var arr = [1, 2, 3, 4, 5, 6, 7, 8, 9]
var res = arr.map(function (item, index, origin) {
   console.log(item, index)
   return item * 10
})
console.log(res)      //The return value is an array enlarged ten times: [10,20,30,40,50,60,70,80,90]

Interview question: Among the common traversal methods of arrays, what is the difference between foreach and map?

Reply:

  • The function of forEach is to traverse the array, and the function of map is to map the array.

  • forEach has no return value, while map has a return value.

  1. filter

  • Syntax: Array.filter(function(item,index,origin){})

  • Function: filter the array (leave what you want)

  • Return value: returns a new array, which stores part of the filtered content of the original array

  • Filter condition: the filter condition is written in the form of return

var arr = [1, 2, 3, 4, 5, 6, 7, 8, 9]
var res = arr.filter(function (item, index, origin) {
    return item > 6
})
console.log(res)  //Return value: [7,8,9]
  1. find

  • Syntax: Array.find(function (item, index, origin){})

  • Function: Find the first item that satisfies the condition in the array

  • Return value: found data, if not found, return undefined

  • The search condition is written in the form of return

ar arr = [1, 2, 3, 4, 5, 6, 7, 8, 9]
var res1 = arr.find(function(item,index,origin){
      return item > 6
 })
console.log(res1)    //The return value is: 7
var res2 = arr.find(function(item,index,origin){
        return item > 10
 })
console.log(res2)   //The value that meets the condition cannot be found, and the return value is: undefined
  1. findIndex

  • Syntax: Array.findIndex(function (item, index, origin){})

  • Function: Find the index of the first item that satisfies the condition in the array

  • Return value: the index of the found data, or -1 if not found

  • The search condition is written in the form of return

var arr = [1, 2, 3, 4, 5, 6, 7, 8, 9]
var res = arr.findIndex(function(item,index,origin){
    return item > 6
})
console.log(res)     //Return value: 6
var res1 = arr.findIndex(function(item,index,origin){
    return item > 60
})
console.log(res1)   //not found, return -1

6.some

  • Syntax: array.some(function (item, index, origin){})

  • Function: to determine whether there is a value that satisfies the condition in the array (at least one)

  • Return value: true/false

  • The judgment condition is written in the form of return

var arr = [1, 2, 3, 4, 5, 6, 7, 8, 9]
var res = arr.some(function (item, index, origin) {
   return item > 7      
})
console.log(res)  //true

7.every

  • Syntax: Array.every(function (item, index, origin){})

  • Function: Determine whether each of the arrays satisfies the condition

  • Return value: true/false

  • The judgment condition is written in the form of return

var arr = [1, 2, 3, 4, 5, 6, 7, 8, 9]
var res = arr.every(function (item, index, origin) {
   return item > 7      
})
console.log(res)  //false

8.reduce

  • Syntax: Array.reduce(function (prev,item, index, origin){}init)

  • prev: Indicates the initial value, or the result of the last operation

  • Function: used to achieve overlay effect

  • Return value: the result of the final superposition

  • Superposition conditions are written in the form of return

Note: For the first value of prev, if the value of init is passed, the value of init is used; if the value of init is not passed, then it is the value of the array [0];

If the value of init is passed, then the number of loops is the length of the array, if no init is passed, the number of loops is the length of the array - 1 times.

var arr = [100,200,300,400]
var res = arr.reduce(function(prev,item,index,origin){
    return prev + item
},0)
console.log(res)    //The return value is: 1000
analyze:
  First loop:
        prev===0(because of using reduce The method is passed a second parameter init);
        item===100(because init Give the value, so item Values ​​start at index 0, which is 100);
        During the first round of code execution, run prev+item,This result will be passed on to the second round prev the value of(100)
  Second cycle:
        prev===100;item===200(The value at index 1);
        return prev+item(300),passed to the third round prev
  The third cycle:
        prev===300;item===300(the value at index 2);
        return prev+item(600),passed to the fourth round prev
 Fourth cycle:
        prev===600;item===400(the value at index 3);
        return prev+item(1000),passed to the fifth round prev
  Because there are no elements in the follow-up, so the loop stops here, and then the last round of calculation prev value(1000)return go out,Receive this value externally, print 1000              
var arr1 = [100,200,300,400]
var res1 = arr1.reduce(function(prev,item,index,origin){
   return prev + item
})
console.log(res1)   //Return value: 1000
analyze:
 First loop:
        prev===100(because no init value, so the first prev The value of is the value at index 0 in the array, which is 100);
        item===200(because no delivery init value, so the first prev The value is the value at index 0, then the first item It is the value at index 1, which is 200);
        During the first round of code execution, run prev+item,This result will be passed on to the second round prev the value of(300)
  Second cycle:
        prev===300;item===300(the value at index 2);
        return prev+item(600),passed to the third round prev
  The third cycle:
        prev===600;item===400(the value at index 3);
        return prev+item(1000),passed to the fourth round prev
  Because there are no elements in the follow-up, so the loop stops here, and then the last round of calculation prev value(1000)return go out,Receive this value externally, print 1000

Tags: Javascript

Posted by Sindarin on Tue, 17 Jan 2023 16:27:08 +0300