What are the commonly used methods of arrays?

There are many array methods that are often used in daily work, here is a summary~

1. reverse( )

Flip array elements

2. sort( )

Sort the array, sort by Unicode encoding by default

3. concat( )

Concatenate multiple arrays

let arr1 = [1,2,3]
let arr2 = [4,5]
let arr = arr1.concat(arr2)
console.log(arr) //[1, 2, 3, 4, 5]

4. slice(start,end)

Intercept array elements

start: start subscript, end: end subscript, excluding the end item, if end is empty, it means intercepted to the end, if the subscript is negative, it means the reciprocal, returns the array composed of the intercepted elements, the original array will not change

let arr = [0,1,2,3,4,5,6,7]
console.log(arr.slice(1,4)) //[1, 2, 3]
console.log(arr.slice(3)) //[3, 4, 5, 6, 7]
console.log(arr.slice(-4,-1)) //[4, 5, 6]
console.log(arr) // [0,1,2,3,4,5,6,7]

5. splice(start,count,v1,v2...)

delete array element

start: the starting subscript, count: the length of the deletion, if count is empty, it means the deletion is at the end, if the subscript is negative, it means the countdown, v1, v2 means the elements added after deletion, return the array composed of deleted elements, the original array will happen Variety

let arr = [0,1,2,3,4,5,6,7]
console.log(arr.slice(1,4)) //[1, 2, 3, 4]
console.log(arr.slice(4)) //[4, 5, 6, 7]
console.log(arr.slice(-3)) //[5, 6, 7]
console.log(arr.splice(1,4,5,6,7)) // [1, 2, 3, 4]  //arr=[0, 5, 6, 7, 5, 6, 7]

6. push( )

Add one or more elements at the end of the array, return the length of the array , and the original array will change

7. unshift( )

Add one or more elements at the beginning of the array, return the length of the array , and the original array will change

8. pop( )

Delete an element at the end of the array, return the deleted element , and the original array will change

9. shift( )

Delete an element at the beginning of the array, return the deleted element , and the original array will change

10. indexOf( )

Find whether it contains an element, if found, return the subscript, if not found, return -1

To be continued~~~

Guess you like

Origin blog.csdn.net/m0_65489440/article/details/128961275