Home >Web Front-end >JS Tutorial >Detailed explanation of JavaScript arrays_javascript skills

Detailed explanation of JavaScript arrays_javascript skills

WBOY
WBOYOriginal
2016-05-16 17:20:271175browse

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

Copy code The code is as follows:
var a1=new 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

Copy code The code is as follows:
var a2=new Array(5);

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

Copy code The code is as follows:
var a3=new Array(4,'hello',new Date( ));

Literal

1. Use square brackets to create an empty array, which is equivalent to calling a parameterless constructor

Copy code The code is as follows:
var a4=[];

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

Copy code The code is as follows:
var a5=[10];

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

Copy code The code is as follows:

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

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

Copy code The code is as follows:

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 an array with initialization parameters, it is best not to include extra "," at the end. Different browsers handle this differently

Copy code The code is as follows:

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

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

Copy code The code is as follows:

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. 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

Copy code The code is as follows:

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


image

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.

Copy code The code is as follows:

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

image

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.

Copy code The code is as follows:

a.length=2
console.log( a);//[1,2]

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

Copy code The code is as follows:

a.length=5;
console.log (a); //[1,2] //There are no 3 undefined

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)

Copy code The code is as follows:

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

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

Copy code The code is as follows:

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

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

image

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

Copy code The code is as follows:

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

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

Copy code The code is as follows:

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 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

Copy code The code is as follows:
var a=new Array(1,2,3,4,5 );

Delete

Specify the first two parameters, you can use splice to delete array elements, which will also bring about index adjustment and length adjustment

Copy code The code is as follows:

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 does not start from 0, the result will be very interesting. There is such an array

Copy code The code is as follows:

var a=new Array();
a[2]=2;
a[3]=3;
a[7]=4;
a[8 ]=5;

image

Copy code The code is as follows:

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


image

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

Copy code The code is as follows:

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#. Its function is to connect the array elements (the object calls its toString() method) into a string using parameters as connectors

Copy code The code is as follows:

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)

Not to be confused with the splice method, slice

Copy code The code is as follows:

var a=new Array(1,2,3, 4,5);
console.log(a); //[1, 2, 3, 4, 5]
console.log(a.slice(1,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 the array. If only one parameter is written, the parameter is returned to the end of the array. , if the parameter appears to be a negative number, count from the end of the array (-3 means the third from the bottom of the array, most people will not do this, but it is useful when you do not know the length of the array and want to discard the last n, but the array length is good Know... , very confusing usage), if start is greater than end, it is worth noting that slice does not change the original array, but returns a new array.

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

Copy code The code is as follows:

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()
The

method is used to reverse the order of the array. The difference from the previous one is that it will modify the original array

Copy code The code is as follows:

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 consecutive or starts with 0, the results need to be noted

Copy code The code is as follows:

var a=new Array();
a [2]=2;
a[3]=3;
a[7]=4;
a[8]=5;

image

Copy code The code is as follows:

a.reverse();


image

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.

Copy code The code is as follows:

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

But. . .

Copy code The code is as follows:

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

Because in alphabetical order, 7 is larger than 10. At this time we need to pass in a custom sorting function

Copy code The code is as follows:

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 sort in C# (design pattern in .NET Framework - applying strategy pattern to sort List), except that the method can be passed in directly. The following content is purely guesswork

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

Finally

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.

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn