This article describes how to implement mutual conversion between Array and String in Javascript, and describes how to use the toString and split Methods in JavaScript, for more information about how to convert Array and String in Javascript, see the following example. We will share this with you for your reference. The details are as follows:
The Array class can be defined as follows:
The Code is as follows:
Var aValues = new Array ();
If you know the length of the array in advance, you can use the parameter to pass the length
The Code is as follows:
Var aValues = new Array (20 );
The following two definitions are the same:
Method 1:
var aColors = new Array();aColors[0] = "red";aColors[1] = "green";aColors[2] = "blue";alert(aColors[0]); // output "red"
Method 2:
Var aColors = new Array ("red", "green", "blue"); // It is equivalent to Array-defined arrays. Alert (aColors [0]); // output "red" too
(1) convert Array to string
The output of the above two array definitions is the same, and a comma separator is found in the middle.
The Code is as follows:
Alert (aColors. toString (); // output "red, green, blue ";
(2) convert string to Array
We found that the Array is converted to a string, with one separator ',' added between the arrays. Therefore, the string to be converted to an Array must have a separator. It can be a comma or another separator.
Var sColors = "red, green, blue"; var aColors = sColors. split (','); // the string is converted to an Array.
I hope this article will help you design JavaScript programs.