Some common methods of arrays and summary of operations during normal work

In normal work, it is necessary to use arrays. Sometimes the data returned from the back end will be re-rendered by the back end if it is not the data front end that conforms to the dom tree rendering or by itself.
Say nothing more. Let's first look at the methods contained in the arrays. Perhaps they are not complete enough. Please add some inadequacies. Is it the purpose of writing this article that everyone grows up with each other?
Common API s for Array in ES5:
1,join()
2,push()
3,pop()
4,splice()
5,indexOf()
6,lastIndexOf()
7,reverse()
8,slice()
9,every()
10,some()
11,reduce()
12,reduceRight()
13,forEach()
14,map()
15,filter()
16,sort()
17,concat()
18,shift()
19,unshift()
20,toLocaleString()
ES6 adds:
1. Use of extended operator...
2,Array.form()
3,Array.of()
4,copyWithin()
5,find()
6,findIndex()
7,fill()
8,entries()
9,flat()
10,flatMap()
11,keys()
12,values()
13. Empty spaces in arrays
Many usages of tips:es6 are unfamiliar to the vegetable chicken. It uses the API of Ruan Yifengda (yes, even the catalog is copied) and adds some opinions on how to use it. When you spray me, you can click on it (I just copied it, you said I won't change it) and attach a link to the document written by Ruan Yifengda. http://es6.ruanyifeng.com/#do...
Don't talk more, just get to the point

1:join method of array object:
The join method converts each object in an array object into a string, splits it together with an incoming parameter string, and returns a string

let Arr = [1,2,3,4]
    console.log(Arr.join(',')) //1,2,3,4
    console.log(Arr.join('-')) //1-2-3-4
    let Arr2 = [1,2,[3,4],[5,6]]
    console.log(Arr2.join(',')) //1,2,3,4,5,6
    //If there are objects in the array, the tostring method will be used first on the object, so the object will be converted to [object Object object], which is generally not done or explained.
    let Arr3 =[1,2,{name:'name1',value:1}]//1,2,[object Object]
    console.log(Arr3.join(','))
 

2:push method of array object:
This method is known to all and appends elements to the end of the array, but it has an inverse argument that you may not notice.

let arr = [1,2,3]
console.log(`push Return parameters:${arr.push(4)} Appended Array Object:${arr} `)//Print result push returns parameter: 4 Appended array object: 1,2,3,4
    
    // Notice that the printed inverse parameter 4 of arr.push(4) does not exist, that is, it returns the length of the stitched array (the length property)
//Array objects can accept all objects, so the push method can take all legal objects (Symbol object doesn't seem to work, or I don't convert it)
    let arr = [1,2]
    arr.push('String')
    arr.push(Symbol('symbol'))
    arr.push({name:'testName',value:'Saurfang'})
    arr.push([3,4])
    arr.push(undefined)
    arr.push(null)
    arr.push(NaN)
    arr.push(new Date())
    console.dir(arr) 

Output results:

2: The pop method of the array object:
The pop() method deletes the last element of the arrayObject, decreases the length of the array by one, and returns the value of the element it deletes.If the array is already empty, pop() does not change the array and returns the undefined value.

//pop
    let arr = [1,2,3]
    console.log(arr.pop()) //3 Returns deleted elements
    console.log(arr) //Delete the last element's array
    let arr2 = [1]
    console.log(arr2.pop())   //1
    console.log(arr2)         //[]
    let arr3 = []
    console.log(arr3.pop())   //undefined
    console.log(arr3)         //[]

3: splice() method of array object
The splice() method adds/deletes items to/from the array and returns the deleted items
The splice method has several parameters that do not need to be filled in each. I borrow w3cschool to give us documentation on the specific parameters

Syntax arrayObject.splice (index, howmany, item1,...., itemX)

Parameters and usage

  • index: Required.Integer specifies where items are added/deleted, and negative numbers specify where items are located at the end of the array.
  • howmany: required.Number of items to delete.If set to 0, the item is not deleted.
  • Item1,..., itemX: Optional.A new item added to the array.
//splice
    let arr =[1,2,3,4]
    // arr.splice(1,2)//Remove two elements from the position of array indexOf 1 and return an array
    console.log(arr.splice(1,2))// [2, 3]
    console.log(arr)  //[1,4]
    let arr2=[1,2,3,4]
    arr2.splice(1,2,666,777,888) //Remove two elements from arr2indexOf1 and insert 666, 777, 888 elements
    console.log(arr2) //[1, 666, 777, 888, 4]
    let arr3 = [1,2,3,4]
    arr3.splice(-1,1,7777)//Delete an element from the end of arr3 and insert 7777 at the deleted element location
    console.log(arr3) //[1, 2, 3, 7777]
    let arr4 = [1,2,3,4]
    arr4.splice(-1,0,6666)//Delete 0 elements from the end of arr4 and insert 7777 at the deleted element location
    console.log(arr4)  //[1, 2, 3, 6666, 4]
    let arr5 = [1,2,3,4]
    arr5.splice(-2,3,9999)
    console.log(arr5)//[1, 2, 9999]

5: The indexOf method of the array object:

Returns the position of the input parameter in the array (first occurrence)
//indexOf

    let arr =['a','b','c','d']
    console.log(arr.indexOf('c'))  //2
    let arr2 = ['a','b','b','b']
    console.log(arr2.indexOf('b')) //1

6: lastIndexOf method of array object:

Returns the position of the input parameter in the array (last occurrence)
The usage is not explained much like indexOf()

7: Array object reverse method:

Reverse the position of elements in an array
//reverse
    let arr = [1,2,3,4]
    arr.reverse()
    console.log(arr) //[4, 3, 2, 1]

8: slice method of array object:

Returns the selected element from an existing array
 Usage: arrayObject.slice(start,end)

  • Start: Required.Specify where to start the selection.If it is a negative number, it specifies the position from the end of the array.That is, -1 is the last element, -2 is the second last element, and so on.
  • Optional.Specify where to end the selection.This parameter is the array subscript at the end of the array fragment.If this parameter is not specified, the sliced array contains all elements from start to end of the array.If this parameter is a negative number, it specifies elements that start at the end of the array.
//slice
    let arr = [1,2,3,4]
    console.log(arr.slice(0,2))//[1, 2] //Return the length of the array where the first element in the arr begins to intercept two lengths
    console.log(arr)//[1, 2, 3, 4]//This method is different from the splice method except that it returns the length of one of the truncations and stitches them together into an array, without changing the original array

9: every method of array object
Retrieves whether each element in an array object meets the requirements

let arr = [10,11,12,13]
    console.log(arr.every(i=>i>10))//Determine if all elements in arr are greater than 10//false
    console.log(arr.every(i=>i>9)) //Determine if all elements in arr are greater than 9//true

10: some method of array object
Retrieve if there are any elements in the array object that match the rules

let arr = [10,11,12,13]
    console.log(arr.some(i=>i<9)) //Determine if an element in arr is less than 9//false
    console.log(arr.some(i=>i<11)) //Determine if elements in arr are less than 11//true

11: reduce method for array objects
The accumulator method, somewhat like the forEach method, traverses objects in an array and returns the final result

//reduce
    let arr = [1,2,3,4,5,6,7,8,9,10]

    console.log( 'Result:'+
        arr.reduce((x,y)=>{
            console.log(`x=>${x}`)
            console.log(`y=>${y}`)
            return x+y
        })
    ) //55

Looking at the output, you can see that the first time you run the callback function, x is 1, y is 2, the second x=3, y=3, the third output is x=6, y=4, so you can see that the first x equals the first element value of the array, the second element is the second element value of the array, and then x is the value returned by the callback function, and Y is the value of arr [number of times]

11: ReducRight method for array objects

//reduceRight
    let arr = [1,2,3,4,5,6,7,8,9,10]

    console.log( 'Result:'+
        arr.reduceRight((x,y)=>{
            console.log(`x=>${x}`)
            console.log(`y=>${y}`)
            return x+y
        })
    ) //55

From the output, you can see that the reduceRight method is the same as the reduce method, followed by appending from the end

12: forEach method for array objects
Method is used to call each element of the array and pass the element to the callback function

let arr = ['aaa','ccc','ddd','eee','bbb']
    arr.forEach((currentValue,index,arr)=>{
        console.log(`index:${index},value:${currentValue}`)
        console.log(arr)
    })
    /*   This is the output
         index:0,value:aaa
         ['aaa','ccc','ddd','eee','bbb']...
         forEach Method traverses the elements in the array. The current Value in the operation callback function is the current element value traversed, the index is the current element index, and the arr is the array returned by the current element
         forEach The method calls each element of the array and passes the element to the callback function.
         This method can be used if every element in an array needs to be manipulated or judged, but is not recommended if traversal requires return

    */

I won't tell you too much. This is usually used more. Everyone basically knows how to use it.
13: map method for array objects
This is similar to the forEach method, except that I wrote it in the code comments
`let arr = ['aaa','ccc','ddd','eee','bbb']

console.log(arr.map((currentValue,index,arr)=>{
    
    return currentValue+index
}))
/*   This is the output
        [aaa1,ccc2,ddd3,eee4,bbb5]
     map Much like the callback method, the forEach method and the forEach method both pass the value of the currently traversed element and the array in which the currently selected element is indexed. The only difference is that the forEach method does not return a value, but the map method returns a new array which is very convenient to add some new child elements to the array (operand array)
*/`

14:The filter method for array objects
Filter method that filters out elements of an array object that conform to custom rules and combines them into a new array to return

//filter
    let arr = [111,222,333,444,555,666]
    console.log(
        arr.filter((currentValue,index,arr)=>{
            return currentValue>333
        })
    ) //Output results [444,555,666]
    /**
     * filter Method entry usage is also required for current Value, index, arr
     * filter A new array is returned that filters out arrays that do not conform to custom rules
     * */

15:sort method of array object

Sorting that is often used for arrays can be defined by passing in a callback function, which is usually used when comparing the size of Number elements. If the elements in the array are of Number type and no callback function is passed in, the original array will be returned. In other words, comparing the size without a callback function is only valid for String types, so if you want to sort pure Number arrays without passing in a callback function, you must firstAll array elements are converted to String type for sorting, not to mention code directly
let arr = [333,11,666,2,8,123,0]
    let arr2 = ['zzz','eee','sss','aaa','ddd']
    console.log(arr2.sort())  // ["aaa", "ddd", "eee", "sss", "zzz"]
    console.log(arr.sort()) //[0, 11, 123, 2, 333, 666, 8]
    //Thus, no callback function is not valid for arrays of pure Number type, so the sort method is sorted by encoding the array elements.

    //Sort pure Number type arrays from smallest to largest
    console.log(arr.sort((a,f)=>{
        return a-f
    }))//[0, 2, 8, 11, 123, 333, 666]
    //Array of pure Number type sorted from large to small
    console.log(arr.sort((a,f)=>{
        return -(a-f)
    }))//[666, 333, 123, 11, 8, 2, 0]

16: Conat method of array object:
Is this method not useful now or let's just say it splits arrays, returns a new array by passing in multiple parameters (at least one), and splits elements into the array instead of the array if one is passed in

let arr = [1,2,3,4,5]
    console.log(arr.concat(6,7,8,[9,10],[11],[12,13]))//[1,2,3,4,5,6,7,8,9,10,11,12,13]

Too many I won't tell you, there's a better way to do this in ES6, which I'll explain in my next blog post

17: shift method for array objects:

That's not very easy to use. I'll just tell you, after all, the most important thing for a family is to be neat and tidy
If the array is empty, the shift() method does nothing and returns an undefined value.


    //shift
    let arr = [1,2,3,4,5]
    console.log(arr.shift())  //1
    console.log(arr)          //[2,3,4,5]
    //Note that this method will change the length of the original array, which is not normally needed

18: unshift method for array objects:
The unshift() method inserts its parameters into the head of the arrayObject and moves the existing elements sequentially to the higher subscripts to make room.The first parameter of this method will become the new element 0 of the array, if there is a second parameter, it will become the new element 1, and so on.(I copied this directly because I don't know how to express it)
Say nothing but code

//unshift
    let arr = [1,2,3,4,5]
    console.log(arr.unshift(6)) //6
    console.log(arr.unshift([7,8,9]))//7

    console.log(arr)  //[[7,8,9],6,1,2,3,4,5]
    //The unshift method returns the new array length, while the shift method returns the first deleted element, both of which change the array length, and the incoming parameter, if it is an array, will not scatter the incoming array elements as the concat method does.

Well, there are only so many array methods I can think of. These are all before es6. There are many new and useful APIs for operation arrays in es6. I'll talk about them in the next blog post, but I'll also talk about some sausage of operation arrays in my usual work. I hope you can point out my opinions. The purpose of writing a blog is not to grow together?I'm just looking for a little chicken to ask you more and your code will never be bug ged.

Keywords: Front-end less Fragment encoding

Added by robogenus on Mon, 20 May 2019 04:33:32 +0300