javascript array

1. Two ways to create an array:

① Use array literals

var arr=[1,2,3];

②Use new Array()

var arr1=new Array(); creates an empty array

Note: var arr1=new Array(2), the 2 here means the length of the array is 2, and there are two empty array elements in it.

var arr2=new Array(2,3) means that there are two array elements 2 and 3.

2. Check whether it is an array:

(1) The instanceof operator can be used to detect whether it is an array

arr instance of Array;

(2) Array.isArray (parameter); the new method of H5 is supported by versions above ie9

Array.isArray(arr);

Flip array:

function reserve(arr){
            if(arr instanceof Array){
                var arr1=[];
                for(var i=arr.length-1;i>=0;i--){
                    arr1[arr1.length]=arr[i];
                }
                return arr1;
            }
            else {
                return 'erro Please enter the array format';
            }
           
        }
        console.log(reserve([1,2,3,4,5]));

3. The method of adding and deleting arrays:

push (parameter,,,,) Add one or more elements at the end, pay attention to modify the original array and return the new length
pop()

Delete the last element of the array and reduce the length by one

(only one can be deleted at a time) (no parameter)

returns the value it removes the element
unshift(parameter 1..) Add one or more elements to the beginning of the array, modify the array and return the new length
shift()

Delete the first element of the array, and reduce the length of the array by 1. No parameters, modify the original array.

(only one can be deleted at a time) (no parameter)

and return the value of the first element

Code example:

var arr=[1,2,3];
console.log(arr.push(4,'pink'));
console.log(arr.unshift('red'));
console.log(arr);

Remove specific numbers:

var arr=[1100,200,300,400,5000];
        var arr1=[];
        for(var i=0;i<arr.length;i++){
            if(arr[i]>500){
                arr1. push(arr[i]);
            }
        }
        console.log(arr1);

4. Array built-in functions:

(1) Array flip: arr.reserse();

(2) Array sorting: arr.sort();

var arr1=[1,10,5,9,7,8];
        arr1. sort(function(a,b){
            return a-b; ascending order
            return b-a; descending order

        });
        console.log(arr1);

5. Array index method:

indexOf() Find the first index of a specified element in the array If it exists, return the index number if it does not exist, return -1
lastindexOf

the last index in the array

(Start searching from the back, that is, when looking for a specific number, output the index number from the first number found in the back)

If there is a return index number, if there is no return -1

6. Array deduplication:

Thoughts: store the numbers in the old array into the new array, keep only one duplicate element; traverse the old array, and then take the old array elements to query the new array, if the element is in the new array Add it if it has not appeared in the new array; use the new array.indexOf() to return -1, which means that the element has not appeared in the new array, so we will add it.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <script>
        function unique(arr){
            var arr1=[];
            for(var i=0;i<arr.length;i++){
                if(arr1. indexOf(arr[i])==-1){
                    arr1. push(arr[i]);
                }
            }
            return arr1;
        }

        var arr2=[1,2,3,4,5,6,6,6,7,8,2];
        var demo=unique(arr2);
        console. log(demo);
    </script>
</head>
<body>
    
</body>
</html>

7. Array object:

(1) Convert an array to a string:

toString() Convert the array to a string, separating each item with a comma Return a string
join(‘separator’)

method is used to convert all elements in the array into a string returns a string

var arr=[1,2,3,4,5];

console.log(arr.toString()); The result is: 1,2,3,4,5

console.log(arr.join(‘-‘)); The result is: 1-2-3-4-5

(2) Connection, interception, deletion

concat() Connect two or more arrays without affecting the original array return a new array
slice() Array intercept slice (begin, end) Return a new array of intercepted items
splice() Array delete splice (Number to delete) Return a new array of deleted items, note that this will affect the original array
var heroes=["Li Bai",'Cai Wenji','Han Xin','Zhao Yun','Zhen Ji','A Ke','Diao Chan' ,'Daji'];
console.log(heroes.slice(1,4))// [ "Cai Wenji", "Han Xin", "Zhao Yun" ] start index is 1 and end index is 4 (not including 4)
console.log(heroes)// Do not change the original array [ "Li Bai", "Cai Wenji", "Han Xin", "Zhao Yun", "Zhen Ji", "A Ke" , "Diao Chan", "Da Ji" ]

splice() syntax: arr.splice(index,howmany,item1,….itemX)

①index is required, an integer, specifying the position of adding and deleting items, using a negative number can start from the specified position at the end of the array

When there is only an index without howmany, it will be deleted to the end by default.

②howmany is required, the number of items to delete, if set to 0, no items will be deleted. When it is less than 0, it is regarded as 0.

③item1,…….itemX are optional, new items added to the array.

var arr=[1,2,3,4,5];
console.log(arr.toString());
console.log(arr.join('-'));
console.log(arr.splice(1,2,[7,8],9));//The result is [2,3]
console.log(arr);//The result is [1,[7,8],9,4,5]
console.log(arr.splice(1,-10,[6,7]));//The result is [], the negative number defaults to 0 and will not be deleted. 

js array splicing method
Method 1: concat method splicing (return a new array)

var a1 = [1,2,3,4,5];

var a2 = [‘a’,’b’,’c’];

var newa = a1.concat(a2);

var arr1=[1,2,3];
var arr2=[2,3,4,5];
var newarr=arr1.concat(arr2);
console.log(newarr);

ResultType: object

concat method: used to connect two or more arrays to generate a new array, the array behind concat is the element of the array when operating, not the array

Method 2: join method splicing (return a new array)

var a1 = [1,2,3,4,5];

var a2 = [‘a’,’b’,’c’];

var newa = a1.join() + ‘,’ + a2.join();

Return results: 1,2,3,4,5,a,b,c

Result type: string

join method: Put all the elements of the array into a string, then connect these strings, and insert a separator string between the two elements to generate. The separator is a comma (‘,’) when join() does not add a separator, and it is separated by the provided symbol when a separator is added in join(‘.’).