js common functions push(), pop(), shift(), unshift(), slice(), splice(), etc.


Recently, I am not very familiar with the usage of some front-end functions. Some functions are easy to confuse. I will summarize them here and share them with my friends:

1. join() function

join() forms the elements in the array into a string, and needs to pass a parameter as a connector. If not passed, the default is a comma.
insert image description here

2. push() function

Add elements one by one at the end of the array, return the length of the result array, can receive any number of parameters, push() modifies the original array.
insert image description here

3. pop() function

pop() removes the last item in the array and returns the removed item. Modify the original array
insert image description here

4. shift() function

shift() deletes the first element of the array, returns the deleted element, and modifies the original array
insert image description here

5. unshift() function

Add elements to the head of the array, return the length of the result array, modify the original array
insert image description here

6. sort() function

Arrange the array in ascending order and modify the original array.
insert image description here
Note:
The sort() method is used for array sorting. The syntax is as follows: array.sort().
After using the sort() method, the order of the original array will be changed (instead of generating a new array, while the original array remains unchanged)
Example One: Sort the character array

    var myarr1=["h","e","l","l","o"];
    myarr1.sort();
    console.log(myarr1);//(5) ['e', 'h', 'l', 'l', 'o']
  1. When there is no parameter in sort, it will compare and sort according to the ASCII codes corresponding to the array elements.
    Example 2: Sort the array of numbers
    var myarr2=[9,5,1,4,6];
    myarr2.sort();
    console.log(myarr2);//(5) [1, 4, 5, 6, 9]

ort() cannot reasonably sort arrays consisting of array elements with more than two digits
Example

    var myarr2=[10,25,3,8];
    myarr2.sort();
    console.log(myarr2);//10 25 3 8

Causes and solutions
Because the sort() method will first call the toString() method of each array data item,
convert it into a string and then compare it. In the string "25"<"3", the
solution is to need The parameter of sort is used, and this parameter is called the comparison function at this time

  1. Parameters of sort() - comparison function
    Example: Use the comparison function to sort an array of numbers correctly
 	var myarr2=[10,25,3,8];
    var mycompare=function (x,y){
    
    
      if(x<y) return -1;
      else if(x>y) return 1
      else return 0;
    };
    myarr2.sort(mycompare);
    console.log(myarr2);//(4) [3, 8, 10, 25]

The parameters of the comparison function
The comparison function will accept two parameters and compare them

  • Returns a negative number if the first argument should come before the second
  • If the first parameter is equal to the second parameter, return 0
  • If the first parameter should be after the second parameter, return a positive number
    Through the comparison function of the above logic, the array will finally be arranged in ascending order.
    If you want to change it into descending order, you only need to return a negative number to return a positive Just count (positive number becomes negative number, negative number becomes positive number)

Comparison functions cannot sort mashup (char+numeric) arrays

  var myarr3=["h",10];
    myarr3.sort(mycompare);
    console.log(myarr3);//(2) ['h', 10]
    myarr3.sort();
    console.log(myarr3);//(2) [10, 'h']

The comparison function cannot be used to compare a string that cannot be converted into a number and the sorting of the array,
because the comparison function will first convert the string into a number and then compare. When the string cannot be converted into a number, the size cannot be compared ( No comparison function, that is, when sort does not add parameters, the comparison is the ASCII value, which can be compared at this time)
Correct usage:

    // 对于不能转换成数字的字符串(字母型字符串),不使用比较参数,直接比较ASCII值
    var myarr3=["h",10];
    myarr3.sort();
    console.log(myarr3);//(2) ['h', 10]
    // 对于可以转换成数字的字符串(数字型字符串),使用比较函数转换成数字再比较
    var myarr4=["23",37,"1",14];
    myarr4.sort(mycompare);
    console.log(myarr4);//(4) ['1', 14, '23', 37]

Summary:
1. When there are both strings and numbers in the array, first check whether the strings are alphabetic or numeric.

2. If it is an alphabetic string, sort does not need to take parameters, and directly compares the ASCII value.
If it is a numeric string, sort takes parameters, so that the comparison function converts the string into a number and then compares

3. How to sort an array composed of objects?
Requirements
The array items are objects, and now the array needs to be sorted according to a certain property of the object

	//要求根据对象属性age对数组进行排序
    var arr=[
      {
    
    age:10,name:'Tom'},
      {
    
    age:8,name:'Jack'},
      {
    
    age:20,name:'Michel'},
      {
    
    age:12,name:'Daniel'},
    ];

Solution: use comparison function

    var compare = function (obj1, obj2) {
    
    
        if (obj1.age < obj2.age) return -1;
        else if (obj1.age > obj2.age) return 1;
        else return 0;
    } 
    console.log(arr.sort(compare));

Effect:

{
    
    age: 8, name: 'Jack'}
{
    
    age: 10, name: 'Tom'}
{
    
    age: 12, name: 'Daniel'}
{
    
    age: 20, name: 'Michel'}

7. reverse() function

The array is reversed.

8. concat() function

Without affecting the original array, an array is copied, and the parameters are added to the end of the copy, so if no parameters are passed, it is equivalent to copying the original array.
insert image description here

9. slice() function

slice() does not affect the original array, and returns a new array with the specified start position - end position of the original array. This position is the subscript of the array, of course it starts from 0. If there is only one parameter, it is the second parameter to the end by default.
insert image description here
As can be seen from the demo, the returned new array is the element that does not contain the end position.
insert image description here
If the second parameter is not passed, it will return to the end by default, and the last one is not included. The parameter is a negative number, which is equivalent to doing the opposite. At this time, it includes the end position and does not include the start position.
insert image description here

10. splice() function

To delete any item element, two parameters are required: the position to be deleted and the quantity to be deleted.
insert image description here
As seen in the demo, splice() returns an array of deleted elements, and the original array is modified.

To insert any item element, three parameters are required: the position to delete, one not to delete and the element to insert.
insert image description here
It turns out that it was inserted before where it was intended to be inserted.

Replacement, in fact, is to delete any item element at the specified position, and then insert any item element.
insert image description here

11. indexOf() & lastIndexOf() function

Find the position of the parameter element in the array, return -1 if not found. The required parameter must be the target element, and there is an optional parameter that is the starting point to start searching. indexOf() searches from the beginning to the end, and lastIndexOf() searches from the end to the beginning.
insert image description here

Guess you like

Origin blog.csdn.net/u014212540/article/details/130887111