The conversion between JS array and string

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

Conversion of arrays to strings

<script type= "Text/javascript" >
var obj= "NEW1ABCDEFG". Replace (/(.)       (? =[^$])/g, "$"). Split (","); String Conversions to arrays

var obj2 = "NEW2ABCDEFG". Split (""); String Conversions to arrays
alert (obj);
alert (obj.length);
Alert (obj instanceof Array);
Alert (Obj.join ("")); Array into a string
</script>

================================================

Operation of JS Array

1. Creation of arrays

var arrayobj = new Array (); Create an array

var arrayobj = new Array ([size]); Create an array and specify the length, note 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, the array is actually variable in all cases, that is, even if the length of 5 is specified, still

You can store the element outside the specified length, note that the length will change accordingly.

2. Access to elements of an array

var testgetarrvalue=arrayobj[1]; Gets the element value of the array

Arrayobj[1]= "This is the new value"; Assigning a new value to an array element

3. Adding array elements

Arrayobj. Push ([Item1 [item2] [... [Itemn]]); /Adds one or more new elements to the end of the array and returns the new length of the array

Arrayobj.unshift ([Item1 [item2 [...] [Itemn]]); /Adds one or more new elements to the beginning of the array, and the elements in the array are automatically moved back, returning

Back array new length

Arrayobj.splice (insertpos,0,[item1[, item2[, ... [, Itemn]]]); /inserts one or more new elements into the specified position of the array, inserting bits

The element automatically moves back and returns "".

4. Deletion of array elements

Arrayobj.pop (); Removes the last element and returns the element value

Arrayobj.shift (); Removes the first element and returns the element value, and the elements in the array are automatically moved forward

Arrayobj.splice (Deletepos,deletecount); Removes the specified number of DeleteCount elements from the specified position, Deletepos, and returns the array form

Removed elements

5. Interception and merging of arrays

Arrayobj.slice (start, [end]); Returns the part of an array as an array, noting that the element of end is not included, and if the end is omitted, the copy

All elements after start

Arrayobj.concat ([item1[, item2[, ... [, Itemn]]]); Concatenate multiple arrays (which can also be strings, or a mixture of arrays and strings)

As an array, returns a new array that is well connected

6, copy of the array

Arrayobj.slice (0); Returns a copy array of the array, note that it is a new array, not a pointer to the

Arrayobj.concat (); Returns a copy array of the array, note that it is a new array, not a pointer to the

7. Sorting of array elements

Arrayobj.reverse (); Reverses the element (the top row to the last and last to the top), returning the array address

Arrayobj.sort (); Sort the array elements, returning the address of the arrays

8. String of array elements

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

toLocaleString, toString, valueOf: Can be seen as a special use of joins, not commonly used

Ii. 3 properties of an array object

1. Length Property

The Length property represents the size of the array, which is the number of elements in it. Because the index of an array always starts with 0, the upper and lower bounds of an array are: 0 and length

-1. Unlike most other languages, the length property of a JavaScript array is variable, which requires special attention. When the length property is set to a larger size

, the state of the entire array does not change in fact, only the length property becomes larger, and when the length property is set earlier than the previous hour, the index in the original array is greater than or

The value of the element equal to length is all lost. Here is an example that shows changing the length property:

var arr=[12,23,5,3,25,98,76,54,56,76];

Defines an array that contains 10 numbers

alert (arr.length); Displays the length of the array 10

arr.length=12; Increase the length of an array

alert (arr.length); The length of the display array has changed to 12

Alert (arr[8]); Displays the value of the 9th element, which is 56

arr.length=5; Reduces the length of the array to 5, and the elements with an index 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 10

Alert (arr[8]); Although the length is restored to 10, the 9th element cannot be retracted, showing "undefined"

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

You can use an undeclared variable in JavaScript, or you can use an undefined array element (an element that has an index that exceeds or equals length), which

, the value of the length property is set to the value of the index of the element being used 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 a 10-digit array, with the alert statement to see its length as 10. An element with an index of 15 is then used to assign

A value of 15, or arr[15]=34, is then used to output the length of the array with the alert statement, resulting in 16. In any case, for developers who are accustomed to strongly typed programming,

, this is a very surprising feature. In fact, an array created using the form new array (), whose initial length is 0, is the operation of an undefined element in it

, the length of the array changes.

As you can see from the above introduction, the length property is so magical that it makes it easy to increase or decrease the capacity of the array. So the depth of the length attribute

Understanding, which can be used flexibly in the development process.

2. Prototype Properties

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 basic set of functions for a class of objects using the prototype property. The new instance of the object "inherits" the action given to the object's prototype.

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

Adds a method to the array object that returns the value of the largest element 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 executes, Y saves the maximum value in the array x, or 6.

3. Constructor properties

Represents a function that creates an object.

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

Description: The constructor property is a member of all objects that have prototype. They include all JScript-intrinsic pairs except the Global and Math objects

Like. 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)//Processing (condition is true).

Or

function MyFunc {

function body.

}

y = new MyFunc;

if (Y.constructor = = MyFunc)//Processing (condition is true).

For arrays:

y = new Array ();

Specific use:

Working with 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 arrays

<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

can be as simple as the above to assign values, you can also like the following:
<script>
var xzy=new Array ();
xzy=[1,2,3,4,5, "Zhiyun", "hehe"];//assigning values to the array Xzy
for (Var i=0;i<xzy.length;i++)
{
Alert (Xzy[i]);
}
</script>
You can also assign values directly to multidimensional arrays
<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
10 11 12 20 21 30 31 40 41

alert (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");//Append to last, or push multiple
Arr.push ("0123");
for (i=0;i<arr.length;i++)
{
if (arr[i]!=null)
Document.writeln (Arr[i]);
}

Pop: pops up last element, LIFO

 var arr=new Array ();
 var S;
 arr[0]= "A1";
 arr[1]= "A2";
 arr[2]= "A3";
 arr[3]= "A4";
 s=arr.pop ();//Eject 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 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 whole behind is moved
 for (i=0;i<arr.length;i++)
 {
  document.write (arr[i]+ ":");
 }
 //: First: Second: a1:a2:a3:a4:
? Shift: POPs the first element, FIFO
 var arr=new Array ();
 var s;
 arr[0]= "A1";
 arr[1]= "A2";
 arr[2]= "A3";
 arr[3]= "A4";
 s=arr.shift ();//eject the first element, pay the value to s, and delete the first element
 alert (s);
 for (i=0;i<arr.length;i++)
 {
  Document.writeln (Arr[i]);
 }
 //display: A2 a3 A4
Join: Concatenate all array contents using the Join method of the array

A join of the

Array (string val) can concatenate the array elements and insert Val in the middle,
to load the contents into an array when the contents of the drop-down box are interactively displayed on the Web page, and then use innerHTML to display the contents out
  <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 you use A.join () directly, the default is to use, split
  </SCRIPT>
Display :
CCTV
SXTV
Tytv
xzy 
connecting strings in this way is much faster than s=s+ "ddd"
Sort: Array sort (small to large)

Var arr=new Array (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 inversion, and sort mates can be used to sort from large to small
 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 permutation
 for (i=0;i<arr.length;i++)
 {
  Document.writeln ( Arr[i]);
 }
 //display: 0123 Zhiyun a4 A3 A2 A1

Slice: Array truncated after assigning to another array (does 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)///From the beginning of element 2nd of the array xzy1 to the end of the stop value of element 4th to turn into an array
for (Var i=0;i<xzy2.length;i++)
{
document.write (xzy2[i]+ ":");//display C Hello
}
You can write it like 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 element 2nd of the array xzy1 to the end of the stop value of element 4th to turn into an array
for (Var i=0;i<xzy2.length;i++)
{
Alert (xzy2[i]);//display C Hello
}
</script>

? Splice: Array truncated or emptied (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 (3,2, "x1", "X2");//2 elements starting with 3rd, replacing with X1 and x2, and re-assigning the replaced values to the array arr2
If there is no parameter "x1", "X2", then the corresponding 2 elements are removed from arr, followed by a forward push
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 empty an 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 as emptying the ARR array and returning to its original state
alert (arr.length);//Display 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]+ ":");//display: A1:A2:A3:A4:A5:A6:B1:B2:B3:
}
? Using map
MAP1:
<script>

var map = {};

map["Zhang San"] = "1362348754";
map["John Doe"] = "0351-98476345";
map["Harry"] = "0358-4873622";

Alert (map["John Doe"]);
</script>

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

var map = new Array ();

map["Zhang San"] = "1362348754";
map["John Doe"] = "0351-98476345";
map["Harry"] = "0358-4873622";

Alert (map["John Doe"]);//display: 0351-98476345
alert (map.length);//map.length shown here as 0


Map[0] = "0358-4873622";
MAP[1] = "0358-4873622";
Map[2] = "0358-4873622";
Alert (map.length);//Here Map.length is displayed as 3
for (var i=0;i<map.length;i++)
{
 document.write (map[i ]);
}
Alert (map["John Doe"]);//display: 0351-98476345
</script>
map3:
var map={"name": "Zhiyun", "gender": "Male", "age" :
map. Marriage = "Married";//You can dynamically add
eval ("map. Nationality = ' Chinese '");//But map. The following identifiers can only be preceded by a character and cannot have-so the global identifier should not be used here
alert (map. Nationality );
//alert (map. Name);//Zhiyun
//alert (map. age);//34
map["ethnic"]= "Han";//You can also assign values as in the first, but this can be done with any string of keys, such as: map["1-2"]= " The Han "; alert (map. Name

)

+ ":" +map["1-2"]);//can also display normally
Alert (map. Name + ":" +map. National);
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 ', Gender: ' Male ', 35: ' Age '";
Eval ("var map={" +s+ "}");
Alert (map["name"]);
You can also nest nested
var map={"person": {"Zhang San": "Male", "Zhao Liu": "Female"},

"Vehicle": {"Santana": "60,000", "Buick": "100,000"},

"Age": 34}
Alert (map. Personnel. Zhao Liu);//female
Alert (map. Vehicle. Santana);//6
Using an array of custom properties
var a=new Array ();
a[0]={};
A[0]. Name = "Zhiyun";
A[0]. age = 32;

a[1]={};
A[1]. Name = "John Doe";
A[1]. Age = 28;
for (Var i=0;i<a.length;i++)
{
Alert (A[i]. Name + ":" +a[i]. Age);
}

Original: http://fp-moon.iteye.com/blog/1186924

The conversion between JS array and string

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.