Home >Web Front-end >JS Tutorial >Detailed explanation of JavaScript arrays_javascript skills
The importance of arrays in programming languages is self-evident. Arrays in JavaScript are also one of the most commonly used objects. Arrays are ordered collections of values. Due to weak types, arrays in JavaScript are very flexible and powerful. Unlike arrays in strongly typed high-level languages such as Java, which can only store elements of the same type or its subtypes, JavaScript can store multiple types of elements in the same array, and the length can also be dynamically adjusted, as the data increases or Reduce automatic changes to array length.
Create array
Create arrays in various ways in JavaScript
Constructor
1. No-parameter constructor, create an empty array
2. A numeric parameter constructor that specifies the length of the array (since the length of the array can be dynamically adjusted, it is not very useful) and creates an array of the specified length
3. Constructor with initialization data, creates array and initializes parameter data
Literal
1. Use square brackets to create an empty array, which is equivalent to calling a parameterless constructor
2. Use square brackets and pass in initialization data, which is equivalent to calling the constructor with initialization data
Note
1. When using the constructor to create an array, if a numeric parameter is passed in, an array with the length of the parameter will be created. If multiple parameters are passed in, an array will be created, and the parameters will be added to the array as initialization data
var a2=new Array(5,6);
console.log(a2.length);//2
console.log(a2); //[5,6]
But using the literal method, no matter how many parameters are passed in, the parameters will be treated as initialization content
var a2=[5,6];
console.log(a2.length);//2
console.log(a2); //[5,6]
2. When creating an array with initialization parameters, it is best not to include extra "," at the end. Different browsers handle this differently
The result of this script running on a modern browser is the same as we imagined, the length is 3, but in the lower version of IE, it is indeed an array with a length of 4, and the last data is undefined
The index and length of the array
The value of the array can be read and written through natural number index access, and the subscript can also be a variable or expression that results in a non-negative integer
Arrays are also objects. The secret why we can use indexes is that the array will convert the index value into the corresponding string (1=>”1”) as the object attribute name
console.log(1 in a1);//true, it is indeed an attribute
The particularity of the index is that the array will automatically update the length attribute. Of course, because JavaScript syntax stipulates that numbers cannot be used as variable names, we cannot use them explicitly. array.1 such format. It can be seen that in fact, negative numbers and even non-numeric "indexes" are allowed, but these will become attributes of the array, not the index
In this way we can see that all indexes are attribute names, but only natural numbers (with maximum values) are indexes. Generally, array out-of-bounds errors will not occur when we use arrays. It is precisely because of this that the index of the array It may not be continuous. When accessing an element whose index does not exist, undefined
is returned.In the above example, although directly assigning a value to a[100] will not affect a[4] or a[99], the length of the array will be affected. The length attribute of the array is equal to the largest index 1 in the array. We know The length attribute of the array is also a writable attribute. When the length attribute value of the array is forcibly set to be less than or equal to the maximum index value, the array will automatically delete the data with indexd greater than or equal to length. Add a few sentences
to the code just now.At this time, you will find that a[2] and a[100] are automatically deleted. Similarly, if length is set to a value greater than the maximum index 1, the array will automatically expand, but no additions will be made to the array. New elements just append empty space at the end
Element addition/removal
Basic method
The above example has used the method of adding elements to the array, just use the index directly (the index does not need to be consecutive)
As mentioned earlier, arrays are also objects, and indexes are just special attributes, so we can use the method of deleting object attributes and use delete to delete array elements
This is similar to directly assigning a[2] to undefined. It will not change the length of the array, nor will it change the corresponding relationship between index and value of other data
Stack method
Some students have always discovered the above example, especially the deletion method, which is not the way we want it to be. We often hope that after deleting an element in the middle, the index of the following elements will be automatically reduced by one, and the length of the array will be reduced by one at the same time. , just like taking one from a stack, the array has already helped us do this operation. Pop and push allow us to use the array first in, last out like using the stack
Queue method
Now that the stack method has been implemented, how can there be fewer first-in-first-out queues? The shift method can delete the smallest element of the array index, and reduce the index of subsequent elements by one, and the length also decreases by one. This can be simulated using shift/push Queue, of course there is an unshift method corresponding to the shift method, which is used to add an element to the head of the array
The ultimate artifact
JavaScript provides a splice method to solve the problem of adding and deleting arrays at once (the two methods can be combined to achieve the replacement effect). The method has three parameters
1. Start indexing
2. Delete the displacement of the element
3. Of course, you can also write multiple new elements to insert
The splice method returns a new array consisting of deleted elements, or an empty array if there is no deletion
Delete
Specify the first two parameters, you can use splice to delete array elements, which will also bring about index adjustment and length adjustment
If the array index does not start from 0, the result will be very interesting. There is such an array
As you can see from the above example, the first parameter of splice is the absolute index value, not relative to the array index. The second parameter is not the number of deleted elements, but the number of times the deletion action is performed, not the The array is actually moved index-wise, but continuously. At the same time, the index of the following elements is adjusted, and the previous index is ignored
Insertion and Replacement
As long as the second parameter of the method, that is, the number of execution times of the deletion action, is set to 0, and the third parameter and later fill in the content to be inserted, splice can perform the insertion operation, and if the second parameter is not 0, it will It becomes deleting and then inserting at that position, which is the replacement effect
join(char)
This method is also available in languages such as C#. Its function is to connect the array elements (the object calls its toString() method) into a string using parameters as connectors
Not to be confused with the splice method, slice
concat(array)
It looks like cutting, but this is really not a phonetic word. The concat method is used to splice arrays. a.concat(b) returns a new array composed of a and b. It also does not modify any of the original arrays. Nor will recursively concatenate arrays within arrays
method is used to reverse the order of the array. The difference from the previous one is that it will modify the original array
Similarly, when the array index is not consecutive or starts with 0, the results need to be noted
sort
The sort method is used to sort the array. When there are no parameters, it will be sorted in ascending order of the alphabet. If it contains undefined, it will be sorted to the end. The object element will call its toString method. If you want to sort according to your own definition , you can pass a sorting method in, which is a very typical strategy pattern. Sort will also change the original array.
But. . .
Because in alphabetical order, 7 is larger than 10. At this time we need to pass in a custom sorting function
sort uses quick sort internally. Every time when comparing the sizes of two elements, if there are no parameters, the alphabet is directly determined. If there are parameters, the two parameters being compared are passed into the custom method and called (Comparing The two numbers will be passed to v1 and v2 of the custom method). If the return value is greater than 0, it means v1>v2. If it is equal to 0, it means v1=v2. If it is less than 0, it means v1
After understanding these, arrays are really amazing. They are powerful and flexible, but there are also certain inconveniences in traversing elements and obtaining element positions. These have been solved in ECMAScript, so you can use them skillfully. It can make our JavaScript elegant and efficient.