JavaScript Array detailed _javascript tips

Source: Internet
Author: User
Tags array length javascript array

The importance of arrays in programming languages is self-evident, and in JavaScript, arrays are one of the most commonly used objects, arrays are ordered collections of values, and because of the weak type, the arrays in JavaScript are flexible and powerful, It's not like a Java. Strong-type advanced language arrays can hold only the same type or its subtype elements, JavaScript may hold multiple types of elements in the same array, and can be dynamically adjusted in length, which can be changed as the data increases or decreases the automatic array length.

Create an array

Create arrays in various ways in JavaScript

Constructors

1. Parameterless constructor, create an empty array

Copy Code code as follows:
var a1=new Array ();

2. A numeric parameter constructor that specifies the length of the array (because the array length can be dynamically adjusted and does not function much), creating an array of the specified length

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

3. Constructors with initialization data, creating arrays and initializing parameter data

Copy Code code as follows:
var a3=new Array (4, ' Hello ', New Date ());

Literal amount

1. Use square brackets to create an empty array, equivalent to calling the parameterless constructor

Copy Code code as follows:
var a4=[];

2. Using the brackets and passing in the initialization data is equivalent to calling the constructor with initialization data

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

Pay attention.

1. If you pass in a numeric argument when you use a constructor to create an array, you create an array of length parameters, and if you pass in more than one, you create an array, and the arguments are added to the array as initialization data

Copy Code code 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 literal methods, regardless of passing in several parameters, the parameters are treated as initialization content

Copy Code code 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 have an extra "," at the end, which is not handled differently in different browsers

Copy Code code as follows:

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

This script runs on a modern browser. The result is 3, as we would imagine, but in a lower version of IE it is a 4-length array, and the last data is undefined

Index and length of an array

The value of an array can be read and write through the natural index access, and the subscript can also be a variable or expression that draws a nonnegative integer

Copy Code code 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 mystery of which we can use the index is that the array converts the index value to the corresponding string (1=> "1") as the object property name

Console.log (1 in A1);//true, really a property
The specificity of the index is that the array automatically updates the Length property, because the JavaScript syntax stipulates that the number cannot be the variable name, so we cannot display a format that uses array.1. This shows that negative numbers, even non-numeric "indexes" are allowed, but these will become the attributes of the array, not the index

Copy Code code as follows:

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


This way we can see that all indexes are property names, but only natural numbers (with the largest) are indexes, we usually do not have array errors when using arrays because of this, the index of the array can not be continuous, access to index does not exist when the element returned undefined

Copy Code code 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

In the above example, although assigning a value directly to a[100] does not affect a[4] or a[99], the length of the array is affected and the array length property equals the largest index+1 in the array, and we know that the length property of the array is also a writable property. When forced to set the length property value of an array to less than or equal to the maximum index value, the array automatically deletes the data indexd greater than or equal to length, appending a few words to the code

Copy Code code as follows:

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

At this point, a[2] and a[100 are automatically deleted, and similarly, if you set the length to a value greater than the maximum index+1, the array expands automatically, but it does not add new elements to an array, just append empty space to the tail.

Copy Code code as follows:

a.length=5;
Console.log (a); [1,2]//No 3 undefined behind

Element Add/Remove

Basic methods

The example above has been used to add elements to the array method, directly using the index can be (index does not need continuous)

Copy Code code as follows:

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

As mentioned earlier, the array is also an object, and the index is only a special property, so we can use delete to delete the element of the array

Copy Code code as follows:

Delete A[2];
Console.log (a[2]); Undefined

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

Stack method

The above example always has the classmate to discover, especially its deletion method, is not we hope the manifestation, we many times want to delete the middle one element, after the element's index all automatically minus one, the array length simultaneously reduced one, as if in one stack took one, Arrays have helped us do this, and pop and push allow us to use the stack as a first and then out using an array

Copy Code code 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 is implemented, how can the first-first out queue be less, the shift method can delete the index of the smallest element of the array, and make the following element index minus one, length also minus one, so that using Shift/push can simulate the queue, Of course, there is a unshift method corresponding to the shift method that adds an element to the head of the array

Copy Code code 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

Ultimate Artifact

JavaScript provides a splice method for one-time resolution of array additions and deletions (these two methods combine to achieve a substitution effect) with three parameters

1. Start index

2. Remove displacement of elements

3. Insert the 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

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

Delete

Specifying the first two parameters, you can use splice to delete the array elements, which also leads to index adjustments and length adjustments

Copy Code code 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 at 0, the result will be interesting, with one such array

Copy Code code as follows:

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

Copy Code code as follows:

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


As you can see in the example above, the first argument for splice is an absolute index value, not an array index, and the second parameter is not the number of deleted elements, but rather the number of deletions that are performed, not by the actual index of the array, but by moving continuously. Adjust the index of the following element at the same time, ignoring the previous index

Insert and replace

As long as the second parameter of the method, that is, the number of times the deletion action is performed is set to 0, the third parameter and then 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 delete and then insert, that is, replace

Copy Code code 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 used in languages such as C #, where the array element (the object calls its ToString () method) is connected to a string using the argument as a connector

Copy Code code 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)

Don't confuse with splice method, slice

Copy Code code 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 a child array in an array. If you write only one argument to return the argument to the end of the array, and if the argument has a negative number, then count from the tail of the array (-3 means the third of the array, the average person will not do so, but not knowing the length of the array, want to discard the latter n when some use But the length of the array is well known .... , well, if start is greater than end to return an empty array, it is worth noting that slice does not change the original array, but instead returns a new array.

Concat (Array)

It looks like a cut, but this is really not a phonetic word, the concat method is used to splice an array, a.concat (b) Returns a new array of A and B, also does not modify any of the original arrays, nor does it recursively connect an array of internal arrays

Copy Code code 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 ()

method is used to reverse the array, which, unlike before, modifies the original array

Copy Code code as follows:

var a=new Array (1,2,3,4,5);
A.reverse ();
Console.log (a); [5, 4, 3, 2, 1]

Similarly, when an array index is not sequential or begins with 0, the result requires attention

Copy Code code as follows:

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

Copy Code code as follows:

A.reverse ();


Sort

The sort method is used to sort the array, and when there are no parameters, the alphabetical order is sorted, and if the containing undefined is queued to the last side, the object element calls its ToString method, and if you want to sort by your own definition, you can pass a sort method in, a typical policy pattern, The same sort will change the original array.

Copy Code code as follows:

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

But...

Copy Code code as follows:

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

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

Copy Code code 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 the sort in C # (the design pattern in the. NET Framework--The application policy pattern is sorted by the list), but it can be directly passed in, and the following are purely speculative

Sort internally uses fast sorting, each time comparing two element sizes without parameters, the alphabet is directly judged, and if there are parameters, the two parameters being compared are passed in to the custom method and invoked (the two numbers being compared are passed to the V1, v2) of the custom method, and if the return value is greater than 0 indicates v1> V2, if equal to 0, means v1=v2, if less than 0, means v1<v2, in fact, we passed the method is to tell sort how to compare two elements who big who is small, as for the sort of moving elements of the process was written, guess the end.

Finally
understand these look at the array is really not ah, that is strong and flexible, but in the traversal element, and get the element location, etc. also have some inconvenience, these have been solved in the ECMAScript, skilled use can make our JavaScript elegant and efficient.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.