JavaScript array detail_javascript tips-js tutorial

Source: Internet
Author: User
Tags javascript array
When learning js, you have to learn its array. This article is organized by salad oil. If you need to learn js arrays, you can refer to the importance of arrays in programming languages, arrays in JavaScript are also one of the most commonly used objects. arrays are ordered sets of values. Due to the weak type, arrays in JavaScript are flexible and powerful, unlike arrays of high-level languages such as Java, JavaScript can store multiple types of elements in the same array, and the length can be dynamically adjusted, the array length can be automatically changed as data increases or decreases.

Create an array

Create arrays in multiple JavaScript methods

Constructor

1. No parameter constructor creates an empty array

The Code is as follows:

Var a1 = new Array ();

2. A Number Parameter constructor that specifies the length of the array (because the length of the array can be dynamically adjusted, the function is not large) to create an array with the specified length

The Code is as follows:

Var a2 = new Array (5 );

3. constructor with initialization data, create an array and initialize parameter data

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 non-argument constructor.

The Code is as follows:

Var a4 = [];

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

The Code is as follows:

Var a5 = [10];

Notes

1. when you use the constructor to create an array, If you input a number parameter, an array with the length of the parameter will be created. If you input multiple parameters, an array will be created and the parameter will be added to the array as the initialization data.

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]

However, no matter how many parameters are input, the parameters are treated as initialization content.

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 using the method with initialization parameters, it is best not to include redundant ",". The processing method is different in different browsers.

The Code is as follows:


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

The running result of this script on modern browsers is the same as we imagined. The length is 3, but in earlier versions, IE does have an array of 4, and the last piece of data is undefined.

Index and length of an array

The value of the array can be read and written through the access of the natural number index. The subscript can also be a variable or expression that produces a non-negative integer.

The Code is as follows:


Var a1 = [1, 2, 4];
Console. log (a1 [0]); // 1
Var I = 1;
Console. log (a1 [I]); // 2
Console. log (a1 [++ I]); // 3

Array is also an object. We can use the index. The mystery is that the array will convert the index value to the corresponding string (1 => "1") as the object property name.

Console. log (1 in a1); // true, which is indeed an attribute
The special feature of the index is that the array will automatically update the length attribute. Of course, because the JavaScript syntax stipulates that numbers cannot be used as variable names, we cannot use the format of array.1. It can be seen that negative numbers, or even non-numeric "indexes" are allowed, but these will become the attribute of the array, rather than the index.

The Code is as follows:


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



In this way, we can see that all indexes are attribute names, but only the natural number (with the maximum value) is the index. Generally, when using arrays, there is no array out-of-bounds error, the index of the array can be non-consecutive. When an element that does not exist in the index is accessed, undefined is returned.

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

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, the array length attribute is equal to the maximum index + 1 in the array. We know that the length attribute of the array is also writable, when the value of the length attribute of the array is set to a value smaller than or equal to the maximum index value, the array will automatically delete the data whose indexd is greater than or equal to the length value.

The Code is as follows:


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

At this time, we will find that a [2] and a [100] are automatically deleted. Similarly, if we set the length to a value greater than the maximum index + 1, the array will automatically expand, however, no new elements are added to the array, but empty spaces are appended to the end.

The Code is as follows:


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

Add/delete Element

Basic Method

The method for adding elements to the array has been used in the above example. You can directly use the index (the index does not need to be continuous)

The Code is as follows:


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

The array is also an object, and the index is only a special attribute, so we can use the delete method to delete the array element.

The Code is as follows:


Delete a [2];
Console. log (a [2]); // undefined

This is similar to assigning a [2] to undefined without changing the array length or the correspondence between indexes and values of other data.

Stack Method

In the above example, some people will find out, especially the deletion method, which is not the expected form. We often want to delete an element in the middle, the index of the following elements is automatically reduced by one, and the array length is reduced by one at the same time. It is like taking one in a stack. The array has already helped us with this operation, pop and push allow us to use the stack so that we can first input and then use the Array

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

Since the stack method has been implemented, how can we reduce the number of first-in-first-out queues? shift can delete the minimum element of the array index and reduce the index of the subsequent elements by one, while length is also reduced by one, in this way, shift/push can be used to 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 header.

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

Ultimate artifact

JavaScript provides a splice Method for adding and deleting arrays at a time (the two methods can be used together to achieve the replacement effect). The method has three parameters.

1. Start Indexing

2. Delete element displacement

3. You can also write multiple new elements.

The splice method returns a new array composed of deletion elements. If no elements are deleted, an empty array is returned.

The Code is as follows:

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

Delete

You can use splice to delete array elements by specifying the first two parameters, which also results in index adjustment and length adjustment.

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

The Code is as follows:


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

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]



The preceding example shows that the first parameter of splice is the absolute index value, instead of the array index. The second parameter is not the number of elements to be deleted, but the number of times the delete action is performed, instead of moving by the actual index of the array, it is moving continuously. At the same time, adjust the index of the subsequent elements.

Insert and replace

As long as the second parameter of the method, that is, the number of execution times of the delete action is set to 0, and the third parameter and the content to be inserted will be filled in later, splice will be able to perform the insert operation, if the second parameter is not 0, it is changed to delete the parameter first and then insert it, that is, the replacement effect.

The Code is as follows:


Var a = new Array (1, 2, 3, 4, 5 );
A. splice (999 );
Console. log (a. length); // 8
Console. log (a); // [1, 9, 99,999, 2, 3, 4, 5]
A. splice (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 C # and other languages to connect the array elements (the object calls its toString () method) to a string using parameters as connectors.

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)

Do not confuse with the splice method, slice

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]


The return method is used to return a part or sub-array in the array. If you write only one parameter to return the end part of the array, if the parameter is negative, then count from the end of the array (-3 indicates the third in the array. The average person will not do this, but it is useful when he does not know the length of the array and wants to discard the last n, but the array length is very good to know ...., if start is greater than end, an empty array is returned. It is worth noting that slice does not change the original array, but returns a new array.

Concat (array)

It looks like a cut, but this is really not a form word. The concat method is used to splice an array,. concat (B) returns a new array composed of a and B. It also does not modify any original array or recursively concatenate the internal array.

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 array order. Different from the previous method, it modifies the original array.

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 continuous or starts with 0, note that

The Code is as follows:


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

The Code is as follows:


A. reverse ();



Sort

The sort method is used to sort arrays. If there is no parameter, the arrays are sorted in ascending alphabetical order. If undefined is included, it is ranked to the end, and the object element calls its toString method, if you want to sort by your own defined method, you can pass in a sorting method. In a typical policy mode, sort will change the original array.

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

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 7 is bigger than 10 in alphabetical order, we need to input a custom sorting function.

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 -- Application policy pattern is sorted by List), but the method can be directly passed in. The following content is purely speculation.

Sort uses quick sorting internally. If there is no parameter when comparing the size of two elements each time, the alphabet is directly determined. If there is a parameter, the two parameters being compared are passed into the custom method and called (the two parameters being compared are passed to the v1 and v2 of the custom method). If the return value is greater than 0, v1> v2, if it is equal to 0, it indicates v1 = v2. If it is smaller than 0, it indicates v1

Last
I have learned about these arrays, but they are powerful and flexible. However, it is inconvenient to traverse elements and obtain element positions. These problems have been solved in ECMAScript, skillful 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.