Examples of common js Array Operations and mutual conversion between arrays and strings, js Array

Source: Internet
Author: User
Tags javascript array

Examples of common js Array Operations and mutual conversion between arrays and strings, js Array

This article describes common operations on js arrays and conversion methods between arrays and strings. We will share this with you for your reference. The details are as follows:

Conversion of arrays and strings

<Script type = "text/javascript"> var obj = "new1abcdefg". replace (/(.)(? = [^ $])/G, "$1 ,"). split (","); // convert string to array var obj2 = "new2abcdefg ". split (""); // convert string to array alert (obj); alert (obj. length); alert (obj instanceof Array); alert (obj. join (""); // convert an array to a string </script>

Common Operations on js Arrays

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 it is not the upper limit, is the length var arrayObj = new Array ([element0 [, element1 [,... [, elementN]); creates an array and assigns a value.

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 array element value 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 arrayObj is returned. 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 (); // remove the last element and return the value of arrayObj. shift (); // remove the first element and return the element value. The elements in the array are automatically moved forward to arrayObj. splice (deletePos, deleteCount); // deletes the specified number of deleteCount elements starting from deletePos in the specified position. The removed elements are returned in an array.

5. truncate and merge Arrays

ArrayObj. slice (start, [end]); // return part of the array in the form of an array. Note that the elements corresponding to the end are not included. If the end is omitted, all the elements after the start are copied to 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 instead of pointing to 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 alert (arr. length); // display the length of the array 10arr. length = 12; // increase the length of the array. alert (arr. length); // The length of the displayed array has changed to 12 alert (arr [8]); // The value of 9th elements is 56arr. length = 5; // reduce the length of the array to 5. The element whose index is equal to or greater than 5 is discarded by 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, show "undefined"

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=[12,23,5,3,25,98,76,54,56,76];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 <. length; I ++) document. writeln (a [I]); </script> multidimensional Array of rows <script> var rows = new Array (); rows [0] = new Array (5 ); rows [1] = new Array (5); rows [0] [0] = "hello"; rows [0] [1] = "cloud "; 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 the xzy value to the array (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 = ["", ["China", "Taiyuan", "zhicloud"], [], [], [], ["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]); // Alibaba Cloud alert (s [2] [0]); // 3 alert (s [2] [1]); /// 3333 alert (s [5] [1] [0]); // aalert (s [5] [1] [2]); // calert (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 (" 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 (); // pop up the last element, pay the value to s, and delete the last element 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 the entire 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 alert (s) is deleted; 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 of the drop-down box is displayed interactively on the webpage, the content can be loaded into the array, use innerHTML to display the content

<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 (. join ('<br>'); // If. join (), which is used by default to split </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 5var xzy2 = xzy1.slice (2, 4 ); // convert the value starting from element 2 of array xzy1 to element 4 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 5var 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 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 (Bytes 0000); // 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 [""] = "0358-4873622"; alert (map [""]); // display: 0351-98476345alert (map. length); // here map. the length is displayed as 0map [0] = "0358-4873622"; map [1] = "0358-4873622"; map [2] = "0358-4873622"; alert (map. length); // here map. the length is 3for (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"; // You can dynamically add eval ("map. nationality = 'zhonghua '"); // But map. the following identifiers can only start with a character and cannot be-so the global identifiers should not be used here alert (map. nationality); // alert (map. name); // Ji zhiyun // alert (map. age); // 34map ["nationality"] = "Han nationality"; // you can assign values as in the first article, but you can use any string as the key, for example: map ["1-2"] = "Han"; alert (map. name + ":" + map ["1-2"]); // 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 six": "female"}, "vehicle": {"santana": "60 thousand ", "Buick": "0.1 million"}, "Age": 34} alert (map. personnel. zhao 6); // female alert (map. vehicles. 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 <. length; I ++) {alert (a [I]. name + ":" + a [I]. age );}

I hope this article will help you design JavaScript programs.

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.