Coding With Fun
Home Docker Django Node.js Articles Python pip guide FAQ Policy

Javascript array common method techniques are fully solved


May 06, 2021 JavaScript


Table of contents


The importance of arrays to program languages need not be said, but in the use of javascript will inevitably need to use array operations, mainly used to encapsulate and manage multiple types of data, in js, arrays can be created using the Array constructor, or using the "quick creation" method, which is also the preferred method. /b30> Arrays in js are also very different from arrays in other languages, so let's focus on some common methods and techniques for array operation in js.


Arrays are ordered collections of values, because of weak types, arrays in JavaScript are very flexible and powerful, unlike Java and other strong types of high-level language arrays can only hold the same type or its subtype elements, JavaScript can hold multiple types of elements in the same array, and the length can also be dynamically adjusted, you can automatically change the length of the array as the data increases or decreases.


Create an array
Create arrays in JavaScript in a variety of ways

The constructor
1. No parameter constructor, create an empty array

var a1=new Array();


2. A numeric parameter constructor that specifies the length of the array (because the length of the array can be adjusted dynamically and does not work very well), and creates an array of the specified length


var a2=new Array(5);

3. Constructors with initialization data, create arrays, and initialize parameter data

var a3=new Array(4,'hello',new Date());


Literally

1. Using square brackets to create an empty array is equivalent to calling a non-parameter constructor

var a4=[];


2. Using parentheses and passing in initialization data is equivalent to calling a constructor with initialization data

var a5=[10];

Note the point

1. When you create an array using a constructor, if you pass in a number argument, you create an array that is long as an argument, and if you pass in more than one, you create an array that is added to the array as initialized data

var a1=new Array(5);
            console.log(a1.length);//5
            console.log(a1); //[] ,数组是空的

            var a2=new Array(5,6);
            console.log(a2.length);//2
            console.log(a2); //[5,6]

However, using a literal approach, no matter how many parameters are passed in, the parameters are treated as initialized content

var a1=[5];
            console.log(a1.length);//1
            console.log(a1); //[5]

            var a2=[5,6];
            console.log(a2.length);//2
            console.log(a2); //[5,6]


2. When creating arrays with initialization parameters, it is best not to end up with extra ",", which is handled differently in different browsers

var a1=[1,2,3,];
console.log(a1.length);
console.log(a1);

This script runs on a modern browser with the same length as we thought, 3, but under the lower version of IE it is an array of 4 lengths, and the last data is underfined



The index and length of the array

The values of the array can be accessed through the natural index for read and write operations, and the subse cursor can also be a variable or expression that produces a non-negative integer

var a1=[1,2,3,4];
console.log(a1[0]); //1
var i=1;
console.log(a1[i]); //2
console.log(a1[++i]); //3

Arrays are also objects, and the secret we can use indexes is that they convert index values to corresponding strings (1?gt;"1") as object property names


console.log(1 in a1);//true,确实是一个属性

Index speciality is that the array automatically updates the legth property, of course, because the JavaScript syntax states that numbers cannot be variable names, so we can't display formats like array.1. This shows that negative numbers, even non-numeric "indexes", are allowed, except that these become the properties of the array, not the index


var a=new Array(1,2,3);
            a[-10]="a[-10]";
            a["sss"]="sss";

Javascript array common method techniques are fully solved

So we can see that all indexes are property names, but only natural numbers (with maximum values) are indexes, and generally we don't have array cross-border errors when we use arrays, which is why the indexes of arrays can be not continuous, returning undefined when accessing elements that don't exist in index


var a=new Array(1,2,3);
            a[100]=100;
            console.log(a.length); //101
            console.log(a[3]); //undefined
            console.log(a[99]); //undefined
            console.log(a[100]); 100

Javascript array common method techniques are fully solved

In the example above, although the direct assignment of a.100 does not affect the length of the array, but the length of the array is affected, the array legth property is equal to the largest index in the array, we know that the array's length property is also a writeable property, when the array's length property value is set to less than or equal to the maximum index value, the array automatically deletes the index is greater than the data. Add a few words to the code just now

a.length=2
            console.log(a);//[1,2]
At this point, you'll find that a's and a'100'are automatically deleted, and by the same to no means, if you set the length to a value greater than the maximum index1, the array expands automatically, but does not add new elements to the array, but simply adds empty space to the tail
a.length=5;
            console.log(a); //[1,2] //后面没有3个undefined

Element add/delete
The basic method


The above example already uses the method of adding elements to the array, just using the index (index does not have to be continuous)

var a=new Array(1,2,3);
            a[3]=4;
            console.log(a);//[1, 2, 3, 4]

The array mentioned earlier is also an object, and the index is just a special property, so we can use the method of removing object properties to delete array elements using delete


delete a[2];
            console.log(a[2]); //undefined

This, similar to assigning the a.2 directly to underfined, does not change the length of the array, nor does it change the index and value correspondence of other data



Javascript array common method techniques are fully solved

Stack method

The above example always has students found, especially its deletion method, is not the form we want to express, we often want to delete the middle element, the back element index is automatically reduced one, array length at the same time minus one, as if in a stack to take one, array has helped us do this way, pop and push can let us use the stack as first-in, second-out use array

var a=new Array(1,2,3);
            a.push(4);
            console.log(a);//[1, 2, 3, 4] 
            console.log(a.length);//4
            console.log(a.pop(a));//4
            console.log(a); //[1, 2, 3] 
            console.log(a.length);//3


The queue method

Since the stack method is implemented, how can the first-in, first-out queue be less, the shift method can delete the array index minimum element, and the later element index is reduced by one, length is also reduced by one, so that the use of shift/push can simulate the queue, of course, with the shift method corresponding to a unshift method, used to add an element to the head of the array

var a=new Array(1,2,3);
            a.unshift(4);
            console.log(a);//[4, 1, 2, 3] 
            console.log(a.length);//4
            console.log(a.shift(a));//4
            console.log(a); //[1, 2, 3] 
            console.log(a.length);//3


The ultimate artifact

JavaScript provides a splice method for solving array additions and deletions at once (the two methods can be replaced together) with three parameters
1. Start indexing

2. Delete the displacement of the element

3. Insert new elements, of course, can also write multiple

The splice method returns a new array of deleted elements, and an empty array is returned without deletion

var a=new Array(1,2,3,4,5);


Delete

Specifying the first two parameters, you can use splice to remove array elements, which also results in index adjustments and length adjustments

var a=new Array(1,2,3,4,5);
            console.log(a.splice(1,3));//[2, 3, 4] 
            console.log(a.length);//2
            console.log(a);//[1,5]
If the array index doesn't start at 0, the results will be interesting, with one such array
var a=new Array();
        a[2]=2;
        a[3]=3;
        a[7]=4;
        a[8]=5;

Javascript array common method techniques are fully solved
console.log(a.splice(3,4)); //[3] 
        console.log(a.length); //5
        console.log(a); //[2: 2, 3: 4, 4: 5]

Javascript array common method techniques are fully solved


As you can see from the example above, the first argument of splice is the absolute index value, not relative to the array index, the second argument is not the number of deleted elements, but how many times the delete action is performed, not by the actual index of the array, but continuously. At the same time adjust the index of the later elements, the previous index ignores



Insert and replace

As long as the second parameter of the method, that is, the number of times the delete action is performed is set to 0, the third parameter and later fill in to insert the content on the insertion operation, and if the second parameter is not 0 then becomes the first to delete and then insert, that is, the replacement effect

var a=new Array(1,2,3,4,5);
       a.splice(1,0,9,99,999);
       console.log(a.length); //8
       console.log(a);//[1, 9, 99, 999, 2, 3, 4, 5] 
       a.splice(1,3,8,88,888);
       console.log(a.length);//8
       console.log(a);//[1, 8, 88, 888, 2, 3, 4, 5]

Common methods

join(char)
This method is also available in languages such as C, which connects array elements (objects call their toString() methods) into a string using parameters as connectors

var a=new Array(1,2,3,4,5);
       console.log(a.join(',')); //1,2,3,4,5 
       console.log(a.join(' ')); //1 2 3 4 5


slice(start,end)

Don't confuse it with the splice method, slice

var a=new Array(1,2,3,4,5);
            console.log(a); //[1, 2, 3, 4, 5] 
            console.log(a.slice(1,2));//2
            console.log(a.slice(1,-1));//[2, 3, 4] 
            console.log(a.slice(3,2));//[]
            console.log(a); //[1, 2, 3, 4, 5]


Method is used to return a fragment or sub-array in an array, if only one argument is written to return parameters to the end of the array, if the argument is negative, then count from the end of the array (-3 means the third inverted array, the average person will not do so, but do not know the length of the array, want to discard the last n when some use, but the array length is very good to know. . . . , good tangled usage), if the start is larger than the end returns an empty array, it is worth noting that the slice does not change the original array, but returns a new array.



concat(array)

Looks like a cut, but this is really not a sound word, and the concat method is used to stitch arrays, and a.concat(b) returns a new array of a and b together, with no modification of any of the original arrays nor recursive connections to the array's internal arrays


var a=new Array(1,2,3,4,5);
            var b=new Array(6,7,8,9);
            console.log(a.concat(b));//[1, 2, 3, 4, 5, 6, 7, 8, 9] 
            console.log(a); //[1, 2, 3, 4, 5] 
            console.log(b); //[6, 7, 8, 9]
reverse()

Method is used to reverse the array, unlike before, it modifies the original array

var a=new Array(1,2,3,4,5);
            a.reverse();
            console.log(a); //[5, 4, 3, 2, 1]
Similarly, when the array index is not continuous or starts at 0, the result needs to be noted
var a=new Array();
        a[2]=2;
        a[3]=3;
        a[7]=4;
        a[8]=5;

Javascript array common method techniques are fully solved

a.reverse();

Javascript array common method techniques are fully solved

sort
The sort method is used to sort arrays, when there are no parameters will be sorted in alphabet ascending order, if there areundefined will be ranked to the last face, the object element will call its toString method, if you want to sort according to their own definition, you can pass a sort method into, very typical policy pattern, the same sort will change the original array.
var a=new Array(5,4,3,2,1);
       a.sort();
       console.log(a);//[1, 2, 3, 4, 5]

But...

var a=new Array(7,8,9,10,11);
       a.sort();
       console.log(a);//[10, 11, 7, 8, 9]
Because 7 is bigger than 10 by alphabetical order, this is when we need to pass in custom sort functions
var a=new Array(7,8,9,10,11);
           a.sort(function(v1,v2){
            return v1-v2;
           });
       console.log(a);//[7, 8, 9, 10, 11]

The principle is similar to the sort in C, except that the method can be passed in directly, and the following is for informational purposes only:



Sort internal use fast sorting, each time you compare the size of two elements without parameters, then directly judge the alphabet, if there are parameters, pass the two parameters being compared into the custom method and call (the two numbers being compared will be passed to the custom method v1, v2), if the return value is greater than 0 for v1,gt;v2, if equal to 0, for v1-v2, if less than 0, for v1-lt;v2, In fact, our incoming method is to tell sort how to compare two elements who are big and who is small, as to sort the process of moving elements people write well.


The js array loops through the method of all elements within the array

The easiest way to traverse an array in js is to use for and then use the arr.length as the maximum value for for, so let's look at some useful examples.


for() traversing the array

<script type="text/javascript">
 <!--
var arr = new Array(13.5,3,4,5,6);
for(var i=0;i<arr.length;i++){
 arr[i] = arr[i]/2.0;
}
alert(arr);
 //-->
 </script>

The for in loop traverses the array

<html>
<body>
<script type="text/javascript">
var x
var mycars = new Array()
mycars[0] = "Saab"
mycars[1] = "Volvo"
mycars[2] = "BMW"
for (x in mycars)
{
document.write(mycars[x] + "<br />")
}
</script>
</body>
</html>

The method of converting js arrays to strings

1, array to string
Array elements need to be connected into strings with a character, as in the example code:

var a, b;
a = new Array(0,1,2,3,4);
b = a.join("-");

2, string to array

The implementation is to cut a string into strings by a character and return them as an array, as follows:

var s = "abc,abcd,aaa";
ss = s.split(",");// 在每个逗号(,)处进行分解。

JavaScript array exercises

If you've mastered the usual methods for JavaScript arrays described above, you can use JavaScript arrays better with the following exercises!

Javascript array operations

With the JavaScript array, we can store multiple data in the same variable.

Javascript multi-dimensional array operations

This exercise allows you to include other arrays in the array

JavaScript uses indexes to find data in an array

You can access the data in the array through the array index as if you were an action string.

Tip: If you need more exercises on JavaScript arrays, move to this site's JavaScript programming practice!