JavaScript array details

  • 2020-03-26 21:20:43
  • OfStack

Array in the programming language of the importance of self-evident, array is also one of the most commonly used objects in JavaScript, an ordered set of value is an array, because of the weak type, JavaScript arrays is very flexible and powerful, not strongly typed arrays in a high-level language such as Java can only store the same type or its child elements, JavaScript in the same array can deposit a variety of types of elements, and it is also can dynamically adjust length, can increase or decrease as the data automatically to do change the array length.

Create an array

Arrays are created in various ways in JavaScript

The constructor

1. No arguments constructor to create an empty array

var a1=new Array();

2. A numeric parameter constructor that specifies the length of the array (which is not significant because it can be dynamically adjusted) to create an array of the specified length

var a2=new Array(5);

3. Constructor with initialization data, creates an array and initializes the parameter data

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


1. Using square brackets to create an empty array is equivalent to calling the argument free constructor

var a4=[];

2. Use the brackets and pass in the initialization data, which is equivalent to calling the constructor with the initialization data

var a5=[10];

Pay attention to the point

1. When using the constructor to create an array, if a numeric parameter is passed in, an array of length is created. If more than one parameter is passed in, an array is created and the parameter is added to the array as initialization data

var a1=new Array(5);
            console.log(a1); //[], the array is empty
            var a2=new Array(5,6);
            console.log(a2); //[5,6]

However, with the literal approach, no matter how many parameters are passed in, the parameters are treated as the initialization content

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

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

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

This script works as expected on modern browsers, with a length of 3, but in lower versions of IE it does have a length of 4, and the last item is undefined

The index and length of an array

The values of an array can be read and written by accessing the natural number index, and the subscript can be a variable or expression that yields 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 to using an index is that the array converts the index value to the corresponding string (1=> 1 ") as the object property name

The console. The log (1 in a1); //true is really an attribute
The special thing about indexing is that the array automatically updates the length property, and of course because JavaScript syntax dictates that Numbers cannot be used as variable names, we cannot display them in a format like array.1. So negative Numbers and even non-numeric "indexes" are allowed, but these become attributes of an array instead of an index

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

< img border = 0 title = image height = 170 Alt = image SRC = "/ /" width = 352 border = 0 >

So we can see that all of the indexes are property names, but only the natural number (which has a maximum) is the index, and in general we don't have array overbounds when we're using an array and that's why the index of the array can be non-contiguous and return undefined when we're accessing elements that don't exist at index

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

< img border = 0 title = image height = 205 Alt = image SRC = "/ /" width = 335 border = 0 >

Although the above example, the direct and assign a [100] will not affect a [4] or [99], but the length of the array, the array length attribute is equal to the array's largest index + 1, we know that the array length is also a writable attribute, when forced to array length attribute value is set to less than or equal to the maximum index value, the array will be deleted automatically indexd greater than or equal to the length of data, add a few words in the code just now


A [2] and a[100] are automatically deleted. Similarly, if the length is set to be greater than the maximum index+1 value, the array will automatically expand, but no new elements will be added to the array, just empty space will be appended to the end

console.log(a); //[1,2] // No back 3 a undefined

Element add/remove

Basic method

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

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

As mentioned earlier, an array is an object, and an index is just a special attribute, so we can delete an array element by deleting an object attribute using delete

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

This is similar to assigning a[2] to undefined. It does not change the length of the array, nor does it change the index and value of other data

< img border = 0 title = image height = 161 Alt = image SRC = "/ /" width = 267 border = 0 >

The stack method

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

Queue method

Since all the stack methods are implemented, how can there be fewer first-in, first-out queues? The shift method can delete the smallest element of the array index, and make the subsequent elements index minus one, and length minus one, so the use of shift/push can simulate the queue. Of course, there is an unshift method corresponding to the shift method, which is used to add an element to the array head

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

The ultimate artifact

JavaScript provides a splice method for dealing with array additions and deletions all at once (the two methods can be combined to achieve the substitution effect), with three arguments

1. Start indexing

2. Remove element displacement

3. Insert new elements, of course, you can also write more than one

The splice method returns a new array of deleted elements, and an empty array if there is no deletion

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


Specifying the first two parameters, you can use splice to delete 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] 

If the array index doesn't start at 0, then the result is interesting, there's an array like this

var a=new Array();

< img border = 0 title = image height = 132 Alt = image SRC = "/ /" width = 209 border = 0 >

console.log(a.splice(3,4)); //[3] 
        console.log(a.length); //5
        console.log(a); //[2: 2, 3: 4, 4: 5]

< img border = 0 title = image height = 86 Alt = image SRC = "/ /" width = 165 border = 0 >

As you can see from the above example, the first parameter of splice is the absolute index value, not relative to the array index, and the second parameter is not the number of deleted elements, but the number of 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 next element, leaving the previous index out of the way

Insert and replace

As long as the second parameter of the method, which is the number of times the delete action is executed, is set to 0, the third parameter and later fill in the content to be inserted, splice can perform the insert operation, and if the second parameter is not 0, it becomes the first place to delete and then insert, which is the substitution effect

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

Commonly used method

The join (char)

This method, also used in languages like C#, concatenates an array element (the object calls its toString() method) into a string using arguments as concatenators

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

Not to be confused 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,-1));//[2, 3, 4] 
            console.log(a); //[1, 2, 3, 4, 5]

Method used in the returned array a fragment or subarray, if only write a parameters returned to the end of the array part, if the parameters appear negative, the tail counting from the array (3 mean array and the third, the average person will not do that, but I don't know the length of the array, want to give up some, with n, after but the array length is very good... If start > end returns an empty array, it is worth noting that slice returns a new array instead of changing the original array.

Concat (array)

The concat method is used to concatenate arrays, and a.concat(b) returns a new array of a and b, again without modifying any of the original arrays, and without recursively concatenating 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]

The inorder () method is used to reverse an array, but it changes the original array

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

Also, when the array index is not continuous or starts at 0, the result needs to be noted

The same code at the page code block index 19

< img border = 0 title = image height = 132 Alt = image SRC = "/ /" width = 209 border = 0 >


< img border = 0 title = image height = 138 Alt = image SRC = "/ /" width = 217 border = 0 >


Sort method is used to sort an array, when no parameters according to the alphabet ascending sort, if contain undefined will be to the end, the object element will call the toString method, if you want to order, according to the definition of himself can pass a sorting method, typical strategy pattern, also will change the original array sort.

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


var a=new Array(7,8,9,10,11);
       console.log(a);//[10, 11, 7, 8, 9]

Because 7 is bigger than 10 in alphabetical order, we need to pass in our custom sort function

var a=new Array(7,8,9,10,11);
            return v1-v2;
       console.log(a);//[7, 8, 9, 10, 11]

The principle is similar to the sort in C# (the design pattern in Framework -- the application policy pattern sorts the List), except that you can pass the method in directly

Sort internally USES quicksort. If there are no parameters when comparing the size of two elements, the alphabet is directly determined. If there are parameters, the two parameters being compared are passed into the custom method and called (the two Numbers being compared will be passed to v1 and v2 of the custom method). V2, if equal to 0, means v1 is equal to v2, if less than 0, means v1< V2, actually the way we passed it in was to tell sort how to compare the two elements which are bigger and which are smaller, and as for sort moving the elements they wrote it down, end of guessing.

The last
It's great to see that arrays are powerful and flexible, but there are also some inconveniences in traversing elements and getting their locations, which have been addressed in ECMAScript, and proficiency in using them can make our JavaScript elegant and efficient.

Related articles: