The common operation of JS array and the conversion of array and string examples _javascript skills

Source: Internet
Author: User
Tags array length array sort javascript array

This paper illustrates the common operation of JS array and the method of mutual transformation between array and string. Share to everyone for your reference, specific as follows:

The transformation of array and string

<script type= "Text/javascript" >
var obj= "NEW1ABCDEFG". Replace (/(.) (? =[^$])/g, "$"). Split (",");
The string is converted to an array of
var obj2 = "NEW2ABCDEFG". Split ("");  The string is converted to an array of
alert (obj);
alert (obj.length);
Alert (obj instanceof Array);
Alert (Obj.join ("")); Array into a string
</script>

Common operations for JS arrays

1, the creation of the array

var arrayobj = new Array (); Create an array of
var arrayobj = new Array ([size]);//Create an array and specify the length, note that is not the upper limit, is the length
var arrayobj = new Array ([element0[, element1[, ... [, ELEMENTN]]]); Create an array and assign a value

To illustrate, although the second method creates an array that specifies the length, in all cases the array is longer, that is, even if you specify a length of 5, you can still store the elements outside the specified length, note: the length changes.

2, access to elements of the array

var testgetarrvalue=arrayobj[1]; Gets the element value of the array
arrayobj[1]= "This is the new value";//give the array element a new value

3, the addition of array elements

Arrayobj. Push ([Item1 [item2 [...] [Itemn]]]); /Adds one or more new elements to the end of the array and returns an array of new length
arrayobj.unshift ([Item1 [item2]. [Itemn]]]); /Adds one or more new elements to the beginning of the array, the elements in the array are automatically moved back, and the new length of the array is returned
Arrayobj.splice (insertpos,0,[item1[, item2[, ...). [, Itemn]]]); /inserts one or more new elements into the array at the specified position, and the element at the insertion point is automatically moved back to "".

4, the deletion of the elements of the array

Arrayobj.pop (); Remove the last element and return the element value
arrayobj.shift ();//Remove the first element and return the element value, and the elements in the array are automatically moved forward
Arrayobj.splice (deletepos,deletecount); Deletes the specified number of DeleteCount elements starting at the specified position, deletepos the removed elements

5, the array of interception and merging

Arrayobj.slice (start, [end]); Returns a portion of an array as an array, noting that the end-corresponding element is not included, and if omitting the end will replicate
all elements arrayobj.concat after start
([item1[, item2[, ...). [, Itemn]]]); Concatenate multiple arrays (or a string, or a mixture of arrays and strings) into an array, returning a new array of connections

6, the copy of the array

Arrayobj.slice (0); Returns an array of copies, noting a new array, not pointing to
arrayobj.concat ();//Returning an array of copies, note that a new array is not pointing

7, the ordering of array elements

Arrayobj.reverse (); Reverse elements (top to last, last row to top), return array address
arrayobj.sort ();//////array element sort

8. String of array elements

Arrayobj.join (separator); Returns a string that connects each element value of an array, separated by a separator in the middle.

toLocaleString, toString, valueof: Can be seen as a special use of join, not commonly used

Two, 3 properties of an array object

1, Length Property

The Length property represents the size of the array, which is the number of elements. Because the index of an array always starts with 0, the upper and lower bounds of an array are: 0 and length-1 respectively. Unlike most other languages, the length property of a JavaScript array is variable, which requires special attention. When the length property is set larger, the state of the entire array does not actually change, only the length property is larger, and when the length property is set to the previous hour, the value of the element whose index is greater than or equal to length in the original array is lost. The following is an example of changing the length property:

var arr=[12,23,5,3,25,98,76,54,56,76];
Defines an array alert (Arr.length) that contains 10 digits,
///Displays the length of the array
arr.length=12;//increases the length of the array
alert (arr.length); Displays the length of the array changed to
alert (arr[8]);//Displays the value of the 9th element,
arr.length=5;//Reduce the length of the array to 5, and the elements indexed equal to or more than 5 are discarded
alert (arr[8]) ; shows that the 9th element has changed to "undefined"
arr.length=10;//Restores the array length to ten
alert (arr[8]);//Although the length is restored to 10, the 9th element cannot be retracted, displaying the Undefined

From the above code we can clearly see the nature of the length property. But the length object can be set not only explicitly, it may also be implicitly modified.

You can use a variable that is not declared in JavaScript, and you can use an undefined array element (an element whose index exceeds or equal to length), at which point the value of the length property is set to the value plus 1 for the element index used. 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 first defines an array of 10 digits, which can be seen by an alert statement of 10. Then the element with index 15 is assigned to 15, or arr[15]=34, and then the length of the array is output by the alert statement, with 16. In any case, this is a surprising feature for developers who are accustomed to strongly typed programming. In fact, an array created with the new Array () has an initial length of 0, and it is an operation that does not define an element in it, which changes the length of the array.

As you can see from the above introduction, the length property is so magical that it makes it easy to increase or decrease the size of the array. Therefore, a thorough understanding of the length attribute is helpful to the flexible application in the development process.

2, prototype property

Returns a reference to the object type prototype. The prototype property is common to object.

Objectname.prototype

The objectname parameter is the name of the object.

Description: Provides a set of basic functions for an object's class with the prototype property. The operation of the new instance of the object, "inherit", gives the object a prototype.

For an array object, use the following example to illustrate the purpose of the prototype property.

Adds a method to the array object that returns the maximum element value in the array. To do this, declare a function, add it to the 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 executes, Y saves the maximum value in the array x, or says 6.

3, constructor property

Represents a function that creates an object.

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

Description: The constructor property is a member of all objects that have prototype. They include all of the JScript intrinsic objects except the Global and Math objects. The constructor property holds a reference to a function that constructs a particular object instance.

For example:

x = new String ("Hi");
if (X.constructor = = String)//To be processed (condition is true).

Or

function MyFunc {
//functions body.
}
y = new MyFunc;
if (Y.constructor = = MyFunc)//To be processed (condition is true).

For arrays:

y = new Array ();

Specific use:

Using 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>
 Multidimensional array
<script>
var rows= new Array ();
Rows[0]=new Array (5);
Rows[1]=new Array (5);
rows[0][0]= "Hello";
Rows[0][1]= "Zhiyun";
if (rows[0][0]!=null)
{
 alert (rows[0][0]);
}
</script>

Array Assignment

You can assign a value as simple as the top, or you can do something like this:

<script>
var xzy=new Array ();
xzy=[1,2,3,4,5, "Zhiyun", "Hey Heh"];//assign a value to the array xzy for
(var i=0;i<xzy.length;i++)
{
 alert (xzy[i));
}
</script>

You can also assign a value directly to a multidimensional array

<script>
var s=["Hello", ["China", "Taiyuan", "Zhiyun"],[3,3333],[4,4444],[5,5555],["0", ["a", "B", "C"]], "CC"];
0        1          2    3    4 5 6
//a
(s); /Hello, China, Taiyuan, Zhiyun, 3,3333,4,4444,5,5555
alert (s[1);//China, Taiyuan, Zhiyun
alert (s[1][2));//Zhiyun
alert (s[2][0)) //3
alert (s[2][1]),//3333
alert (s[5][1][0),//a
alert (s[5][1][2)),//c
alert (s[6));//cc
</script>

Push: Data can be appended to the last element

var arr=new Array ()
arr[0]= "XBC1";
Arr[1]= "BCX2";
Arr[2]= "CCTV3";
Arr[3]= "XCTV4";
Arr.push ("Zhiyun"), or to the last append, can also push multiple
arr.push ("0123");
for (i=0;i<arr.length;i++)
{
 if (arr[i]!=null)
 Document.writeln (Arr[i]);
}

POPs: pops up last element, LIFO first

var arr=new Array ();
 var s;
 arr[0]= "A1";
 arr[1]= "A2";
 arr[2]= "A3";
 arr[3]= "A4";
 S=arr.pop ()//pops up the last element, pays the value to S, and deletes the last element
 alert (s);
 for (i=0;i<arr.length;i++)
 {
 Document.writeln (arr[i]);
 }
 Show: A1 A2 A3

Unshift: Before inserting to the first,

 var arr=new Array ();
 var s;
 arr[0]= "A1";
 arr[1]= "A2";
 arr[2]= "A3";
 arr[3]= "A4";
 Arr.unshift ("First", "second");//Before the first element is inserted, the subsequent whole is moved to
 (i=0;i<arr.length;i++)
 {
 document.write (arr[i) +":");
 }
 Show: First: Second: a1:a2:a3:a4:

Shift: Eject the first element, advanced first

 var arr=new Array ();
 var s;
 arr[0]= "A1";
 arr[1]= "A2";
 arr[2]= "A3";
 arr[3]= "A4";
 S=arr.shift ()//pops up the first element, pays the value to S, and deletes the first element
 alert (s);
 for (i=0;i<arr.length;i++)
 {
 Document.writeln (arr[i]);
 }
Show: A2 A3 A4

Join: Connect all the array contents using the Join method of the array

The join of an array (string val) can concatenate an array element and insert the Val in the middle, loading the contents into an array when the dropdown box is displayed interactively on a Web page, and then using innerHTML to display the content in the

<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 directly with A.join (), the default will be used, split
</script>

Show:

cctv
Sxtv
Tytv
Xzy

Connecting strings in this way is much faster than s=s+ "DDD"

Sort: Array sort (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 reverse, and sort in conjunction with can be achieved from large to small sort

 var arr=new Array ()
 arr[0]= "A1";
 arr[1]= "A2";
 arr[2]= "A3";
 arr[3]= "A4";
 Arr.push ("Zhiyun");
 Arr.push ("0123");
 Arr.sort ();
 Arr.reverse ();//Array reverse-arrange for
 (i=0;i<arr.length;i++)
 {
 Document.writeln (arr[i]);
 }
 Showing: 0123 Zhiyun a4 A3 A2 A1

Slice: The array is truncated and assigned to another array (without changing 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);//From the beginning of the 2nd element of the array xzy1 to the end of the 4th element stop, turn to an array For
(var i=0;i<xzy2.length;i++)
{
 document.write (xzy2[i]+ ":");//show C Hello
}

I can write that.

<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);// From the beginning of the array xzy1 2nd element to the end of the 4th element stop, turn to an array for
(var i=0;i<xzy2.length;i++)
{
 alert (xzy2[i]);/Show C Hello
}
</script>

Splice: Array truncation or emptying (changing 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 (3,2, "x1", "X2");//2 elements starting from 3rd, replaced with X1 and x2, and re-assigned to array arr2
 //If there is no argument "x1", "X2", The corresponding 2 elements are removed from the arr, followed by a forward for
 (i=0;i<arr.length;i++)
 {
 document.write (arr[i]+ ":"), and/or displayed: A1:a2:a3: X1:X2:A6:
 }
 document.write ("<br/>");
 for (i=0;i<arr2.length;i++)
 {
 document.write (arr2[i]+ ":");//Show: A4:a5:
 }

Using splice to empty 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,100000000);//Can be understood to empty the arr array and back to the initial state
 alert (arr.length);/Show 0

Concat: Array Connection

 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]+ ":");//Show: A1:a2:a3:a4:a5:a6:b1:b2:b3:
 }

Using map

MAP1:

<script>
var map = {};
map["john"] = "1362348754";
Map["dick"] = "0351-98476345";
map["Harry"] = "0358-4873622";
Alert (map["Dick"]);
</script>

With map={} You can empty the map;

MAP2:

<script>
var map = new Array ();
map["john"] = "1362348754";
Map["dick"] = "0351-98476345";
map["Harry"] = "0358-4873622";
Alert (map["Dick"]);//display: 0351-98476345
alert (map.length);//here Map.length Display as 0
map[0] = "0358-4873622";
MAP[1] = "0358-4873622";
MAP[2] = "0358-4873622";
alert (map.length);//Here Map.length shown as 3 for
(var i=0;i<map.length;i++)
{
 document.write (map[i]);
alert (map["Dick"]);//display: 0351-98476345
</script>

MAP3:

var map={"name": "Zhiyun", "gender": "Male", "Age": "A" is "married
";/can dynamically add
eval ("map. Nationality = ' Zhonghua '"); The identifier that follows can only start with a character and cannot have--so global identifiers are not appropriate to use here
alert (map. nationality);
Alert (map. Name);//Zhiyun
//alert (map. age);//34
map["nationality"]= "Han";//can also be assigned as in the first article, but this can be done with any string, such as: map["1-2"]= " Han "; alert (map. Name
+": "+map[" 1-2 "]);//can also display
alert (map. Name +": "+map. Nationality);
for (var colname in map)
{
 alert (colname);//name Sex age marriage no
} for
(var colname in map)
{
 alert ( Map[colname]);//Zhiyun male 34 married
}

I can do that.

var s= "' Name ': ' Zhiyun ', ' gender ': ' Male ', 35: ' Age '";
Eval ("var map={" +s+ "}");
Alert (map["name"]);

Or

var s= "Name: ' Zhiyun ', Sex: ' Male ', 35: ' Age '";
Eval ("var map={" +s+ "}");
Alert (map["name"]);

You can also nest

var map={"Personnel": {"john": "Male", "Zhao Liu": "Female"},
"vehicle": {"Santana": "60,000", "Buick": "100,000"},
"age": +
alert (map. Personnel. Zhao Liu);
alert (map. Vehicle. Santana);//6 million

An array that uses a custom property

var a=new Array ();
a[0]={};
A[0]. Name = "Zhiyun";
A[0]. Age =32;
a[1]={};
A[1]. Name = "Dick";
A[1]. Age =28;
for (Var i=0;i<a.length;i++)
{
 alert (A[i]. Name + ": +a[i]. Age);


I hope this article will help you with JavaScript programming.

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.