JS Array Operations

Source: Internet
Author: User
Tags javascript array

I have been using Js for a long time, but I have never gotten into the JS array form. During this period of time, there were a lot of projects that used arrays. I thought JavaScript could do nothing, but I was so worried that I could learn it! Haha.

1. Create an array

VaR arrayobj = new array (); // create an array

VaR arrayobj = new array ([size]); // create an array and specify the length. Note that the length is not the upper limit.

VaR arrayobj = new array ([element0 [, element1 [,... [, elementn]); Create an array and assign values

It should be noted that, although the second method creates an array with a specified length, the array actually gets longer in all cases, that is, even if the length is 5, you can still store elements outside the specified length. Note: The length will change accordingly.

2. Access to array elements

VaR testgetarrvalue = arrayobj [1]; // obtain the element value of the array.

Arrayobj [1] = "this is a new value"; // assign a new value to the array element

3. Add array elements

Arrayobj. Push ([Item1 [item2 [... [itemn]); // Add one or more new elements to the end of the array and return the new length of the array.

Arrayobj. unshift ([Item1 [item2 [... [itemn]); // adds one or more new elements to the array. The elements in the array are automatically removed and the new length of the array is returned.

Arrayobj. splice (insertpos, 0, [Item1 [, item2 [,... [, itemn]); // insert one or more new elements to the specified position of the array. The inserted element is automatically removed and "" is returned "".

4. Deletion of array elements

Arrayobj. Pop (); // removes the last element and returns the value of this element.

Arrayobj. Shift (); // removes the first element and returns the element value. The elements in the array are automatically moved forward.

Arrayobj. splice (deletepos, deletecount); // deletes the specified number of deletecount elements starting from deletepos in the specified position. The removed elements are returned in the array format.

5. truncate and merge Arrays

Arrayobj. Slice (START, [end]); // return part of the array in the form of an array. Note that the end element is not included. If the end is omitted, all elements after the start are copied.

Arrayobj. concat ([Item1 [, item2 [,... [, itemn]); // concatenates multiple arrays (or strings, or arrays and strings) into an array and returns a new connected array.

6. Copy an array

Arrayobj. Slice (0); // returns the copy array of the array. Note that it is a new array, not pointing

Arrayobj. Concat (); // returns the copy array of the array. Note that it is a new array, not pointing

7. Sorting of array elements

Arrayobj. Reverse (); // returns the array address.

Arrayobj. Sort (); // sorts array elements and returns the array address.

8. stringized array elements

Arrayobj. Join (separator); // returns a string that connects each element value of the array and is separated by separator.

Tolocalestring, tostring, valueof: can be considered as a special use of join, not commonly used

 

2. Three attributes of an array object

1. Length attribute

The Length attribute indicates the length of the array, that is, the number of elements. Because the index of an array always starts from 0, the upper and lower limits of an array are: 0 and length-1. Unlike most other languages, the Length attribute of the Javascript array is variable, which requires special attention. When the Length attribute is set to a greater value, the status of the entire array does not actually change, except that the Length attribute becomes larger. When the Length attribute is set to an hour later than the original value, all the values of the elements whose indexes are greater than or equal to the length in the original array are lost. The following is an example of changing the Length attribute:

VaR arr = [,];

// Defines an array containing 10 numbers

Alert (ARR. Length); // display the length of the array by 10

Arr. Length = 12; // increase the length of the array.

Alert (ARR. Length); // display that the length of the array has changed to 12

 

Alert (ARR [8]); // displays the value of the 9th elements, 56

Arr. Length = 5; // reduce the length of the array to 5. elements whose index is equal to or greater than 5 are discarded.

Alert (ARR [8]); // display that 9th elements have changed to "undefined"

Arr. Length = 10; // restore the array length to 10

Alert (ARR [8]); // although the length is restored to 10, 9th elements cannot be recovered, and "undefined" is displayed"

From the code above, we can clearly see the nature of the Length attribute. However, the length object can be explicitly set and may be implicitly modified. Javascript can use an undeclared variable, or an undefined array element (an element whose index exceeds or is equal to length, the value of the Length attribute is set to the value of the used element index plus 1. For example, the following code:

VaR arr = [,];

Alert (ARR. Length );

Arr [15] = 34;

Alert (ARR. Length );

The Code also defines an array containing 10 numbers. The alert statement shows that the length is 10. Then, an element with an index of 15 is used and assigned a value of 15, that is, arr [15] = 34. Then, the array length is output using the Alert statement, and the result is 16. In any case, this is a surprising feature for developers who are used to strong-type programming. In fact, the initial length of an array created in the form of new array () is 0, and the length of the array changes only when no element is defined.

From the above introduction, we can see that the Length attribute is so magical that it can be used to conveniently increase or decrease the array capacity. Therefore, an in-depth understanding of the Length attribute can be used flexibly in the development process.

2. Prototype attributes

Returns a reference to an object type prototype. The prototype attribute is common to objects.

Objectname. Prototype

The objectname parameter is the name of the object.

Note: The prototype attribute is used to provide a set of basic functions of the object class. The new instance of the object "inherits" the operation that is granted to the object prototype.

The following example describes the purpose of the prototype attribute for array objects.

Add a method to the array object to return the maximum element value in the array. To do this, declare a function, add it to array. prototype, and use it.

Function array_max ()

{

VaR I, max = This [0];

For (I = 1; I <this. length; I ++)

{

If (max <this [I])

Max = This [I];

}

Return Max;

}

Array. Prototype. max = array_max;

VaR x = new array (1, 2, 3, 4, 5, 6 );

Var y = x. Max ();

After the code is executed, y saves the maximum value in array X, or 6.

3. constructor attributes

The function that creates an object.

Object. constructor // object is the name of an object or function.

Note: The constructor attribute is a member of all objects with prototype. They include all inherent JScript objects except global and math objects. The constructor attribute stores references to the functions used to construct a specific object instance.

For example:

X = new string ("hi ");

If (X. constructor = string) // process (the condition is true ).

Or

Function myfunc {

// Function body.

}

Y = new myfunc;

If (Y. constructor = myfunc) // process (the condition is true ).

For arrays:

Y = new array ();

 

 

Specific use:

 

Use Arrays
? Basic operations
<SCRIPT>
VaR A = new array ("CCTV", "sxtv", "tytv ");
VaR A = new array (3 );
VaR A = new array ();
A [0] = "CCTV ";
A [1] = "sxtv ";
A [2] = "tytv ";
A [3] = "xzy ";
For (I = 0; I <A. length; I ++)
Document. writeln (A [I]);
</SCRIPT>
? Multi-dimensional array

<SCRIPT>
VaR rows = new array ();
Rows [0] = new array (5 );
Rows [1] = new array (5 );

Rows [0] [0] = "hello ";
Rows [0] [1] = "Zhi zhiyun ";

If (rows [0] [0]! = NULL)
{
Alert (rows [0] [0]);
}

</SCRIPT>

Array assignment

You can assign values in a simple order as above, or as below:
<SCRIPT>
VaR xzy = new array ();
Xzy = [1, 2, 3, 4, 5, "Zhi zhiyun", ""]; // assign values to the array xzy
For (VAR I = 0; I <xzy. length; I ++)
{
Alert (xzy [I]);
}
</SCRIPT>
You can also directly assign a value to a multi-dimensional array.
<SCRIPT>
VaR S = ["hello", ["China", "Taiyuan", "Zhi zhiyun"], [], [], [], ["0 ", ["A", "B", "C"], "cc"];
// 0 1 2 3 4 5 6
// 10 11 12 20 21 30 31 40 41

Alert (s); // hi, Taiyuan, China, Yi zhiyun, 3,3333, 4,4444, 5,5555
Alert (s [1]); // China, Taiyuan, Yi zhiyun
Alert (s [1] [2]); // min zhiyun
Alert (s [2] [0]); // 3
Alert (s [2] [1]); // 3333
Alert (s [5] [1] [0]); //
Alert (s [5] [1] [2]); // C
Alert (s [6]); // CC
</SCRIPT>

Push: data can be appended to the final element.

VaR arr = new array ()
Arr [0] = "xbc1 ";
Arr [1] = "bcx2 ";
Arr [2] = "cctv3 ";
Arr [3] = "xctv4 ";
Arr. Push (" Zhi cloud"); // append to the end, you can also push multiple
Arr. Push ("0123 ");
For (I = 0; I <arr. length; I ++)
{
If (ARR [I]! = NULL)
Document. writeln (ARR [I]);
}

Pop: the last element is displayed.

VaR arr = new array ();
VaR S;
Arr [0] = "A1 ";
Arr [1] = "A2 ";
Arr [2] = "A3 ";
Arr [3] = "A4 ";
S = arr. Pop (); // The last element is displayed, the value is paid to S, and the last element is deleted.
Alert (s );
For (I = 0; I <arr. length; I ++)
{
Document. writeln (ARR [I]);
}
// Display: A1 A2 A3
Unshift: before the first one,

VaR arr = new array ();
VaR S;
Arr [0] = "A1 ";
Arr [1] = "A2 ";
Arr [2] = "A3 ";
Arr [3] = "A4 ";
Arr. unshift ("first", "second"); // insert it before the first element, and then move it back.
For (I = 0; I <arr. length; I ++)
{
Document. Write (ARR [I] + ":");
}
// Display: First: Second: A1: A2: A3: A4:
? Shift: the first element is displayed.
VaR arr = new array ();
VaR S;
Arr [0] = "A1 ";
Arr [1] = "A2 ";
Arr [2] = "A3 ";
Arr [3] = "A4 ";
S = arr. Shift (); // The first element is displayed, the value is paid to S, and the first element is deleted.
Alert (s );
For (I = 0; I <arr. length; I ++)
{
Document. writeln (ARR [I]);
}
// Display: A2 A3 A4
Join: concatenates all the array content using the join method of the array.

The join (string Val) of the array can connect the array elements and insert Val in the middle,
When the content in the drop-down box is displayed interactively on the webpage, the content can be loaded into the array and then displayed in innerhtml.
<SCRIPT>
VaR A = new array ("CCTV", "sxtv", "tytv ");
VaR A = new array (3 );
VaR A = new array ();
A [0] = "CCTV ";
A [1] = "sxtv ";
A [2] = "tytv ";
A [3] = "xzy ";
Document. writeln (A. Join ('<br>'); // If a. Join () is used directly, it is separated
</SCRIPT>
Display:
CCTV
Sxtv
Tytv
Xzy
The connection string in this way is much faster than S = S + "DDD"
Sort: array sorting (from small to large)

VaR arr = new array (1000)
Arr [0] = "xbc1 ";
Arr [1] = "bcx2 ";
Arr [2] = "cctv3 ";
Arr [5] = "xctv4 ";
Arr. Sort ();
For (I = 0; I <arr. length; I ++)
{
If (ARR [I]! = NULL)
Document. writeln (ARR [I]);
}
? Reverse: array reversely, which can be used with sort to sort data in ascending order.
VaR arr = new array ()
Arr [0] = "A1 ";
Arr [1] = "A2 ";
Arr [2] = "A3 ";
Arr [3] = "A4 ";
Arr. Push ("Alibaba Cloud ");
Arr. Push ("0123 ");
// Arr. Sort ();
Arr. Reverse (); // array reverse Arrangement
For (I = 0; I <arr. length; I ++)
{
Document. writeln (ARR [I]);
}
// Display: 0123 Ma zhiyun A4 A3 A2 A1

Slice: assign a value to another array after array truncation (do not change the original array)
VaR xzy1 = new array ();
Xzy1 = ["A", "B", "C", "hello", "USA", "eng"];
// 0 1 2 3 4 5
VaR xzy2 = xzy1.slice (2, 4); // convert the stop value from element 2 of array xzy1 to an array
For (VAR I = 0; I <xzy2.length; I ++)
{
Document. Write (xzy2 [I] + ":"); // display C hello
}
It can also be written in this way.
<SCRIPT>
VaR xzy1 = new array ();
Xzy1 = ["A", "B", "C", "hello", "USA", "eng"];
// 0 1 2 3 4 5
VaR xzy2 = array. Prototype. Slice. Call (xzy1, 2, 4); // convert the stop value from element 2 of array xzy1 to an array
For (VAR I = 0; I <xzy2.length; I ++)
{
Alert (xzy2 [I]); // displays C hello
}
</SCRIPT>

? Splice: truncates or clears an array (changes the original array)
VaR arr = new array ();
VaR S;
Arr [0] = "A1 ";
Arr [1] = "A2 ";
Arr [2] = "A3 ";
Arr [3] = "A4 ";
Arr [4] = "A5 ";
Arr [5] = "A6 ";
VaR arr2 = arr. splice (, "X1", "X2"); // two elements starting from 3, replaced with X1 and X2, and assign the replaced value to the array arr2.
// If there is no parameter "X1", "X2", the corresponding two elements will be deleted from arr.
For (I = 0; I <arr. length; I ++)
{
Document. Write (ARR [I] + ":"); // display: A1: A2: A3: X1: X2: A6:
}

 
Document. Write ("<br/> ");
For (I = 0; I <arr2.length; I ++)
{
Document. Write (arr2 [I] + ":"); // display: A4: A5:
}
? Use splice to clear the Array
VaR arr = new array ();
Arr [0] = "A1 ";
Arr [1] = "A2 ";
Arr [2] = "A3 ";
Arr [3] = "A4 ";
Arr [4] = "A5 ";
Arr [5] = "A6 ";
Alert (ARR. Length); // display 6
Arr. splice (0,); // it can be understood as clearing the ARR array and returning to the initial state.
Alert (ARR. Length); // display 0

? Concat: array join
VaR arr = new array ();
VaR S;
Arr [0] = "A1 ";
Arr [1] = "A2 ";
Arr [2] = "A3 ";
Arr [3] = "A4 ";
Arr [4] = "A5 ";
Arr [5] = "A6 ";
VaR arr2 = ["B1", "B2", "B3"];
VaR arr3 = arr. Concat (arr2 );
For (I = 0; I <arr3.length; I ++)
{
Document. Write (arr3 [I] + ":"); // display: A1: A2: A3: A4: A5: A6: B1: B2: B3:
}
? Use Map
Map1:
<SCRIPT>

VaR map = {};

Map ["Zhang San"] = "1362348754 ";
Map ["Li Si"] = "0351-98476345 ";
Map ["Wang Wu"] = "0358-4873622 ";

Alert (Map ["Li Si"]);
</SCRIPT>

Use Map = {} to clear the map;
MAP2:
<SCRIPT>

VaR map = new array ();

Map ["Zhang San"] = "1362348754 ";
Map ["Li Si"] = "0351-98476345 ";
Map ["Wang Wu"] = "0358-4873622 ";

Alert (Map [""]); // display: 0351-98476345
Alert (Map. Length); // here map. length is displayed as 0

Map [0] = "0358-4873622 ";
Map [1] = "0358-4873622 ";
Map [2] = "0358-4873622 ";
Alert (Map. Length); // here map. length is 3
For (VAR I = 0; I <map. length; I ++)
{
Document. Write (Map [I]);
}
Alert (Map [""]); // display: 0351-98476345
</SCRIPT>
Map3:
VaR map = {"name": "Min zhiyun", "gender": "male", "Age": 34}
Map. Marital status = "married"; // dynamically add
Eval ("map. Nationality = 'zhonghua '"); // However, the identifiers after map. can only start with a character and cannot have-so the global identifiers should not be used here
Alert (Map. Nationality );
// Alert (Map. Name); // Ji zhiyun
// Alert (Map. Age); // 34
Map ["ethnic"] = "Han"; // you can assign values as in the first article. However, you can use any string as a key, for example: map ["1-2"] = "Han"; alert (map. name + ":" + map ["1-2"]); // can be displayed normally
Alert (Map. Name + ":" + map. Ethnicity );
For (VAR colname in map)
{
Alert (colname); // name, gender, age, marital status
}
For (VAR colname in map)
{
Alert (Map [colname]); // Yao zhiyun male 34 married
}
You can also
VaR S = "'name': 'zhi Yun ', 'Gender': 'male', 35: 'age '";
Eval ("Var map = {" + S + "}");
Alert (Map ["name"]);
Or
VaR S = "Name: 'zhi Yun ', Gender: 'male', 35: 'age '";
Eval ("Var map = {" + S + "}");
Alert (Map ["name"]);
Can also be nested
VaR map = {"Personnel": {"Zhang San": "male", "Zhao Liu": "female "},

"Vehicle": {"santana": "60 thousand", "Buick": "0.1 million "},

"Age": 34}
Alert (Map. Personnel. Zhao 6); // female
Alert (Map. vehicle. Santana); // 60 thousand
Use an array of custom Properties
VaR A = new array ();
A [0] = {};
A [0]. Name = "Ji zhiyun ";
A [0]. Age = 32;

A [1] = {};
A [1]. Name = "Li Si ";
A [1]. Age = 28;
For (VAR I = 0; I <A. length; I ++)
{
Alert (A [I]. Name + ":" + A [I]. Age );
}

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.