Home > Web Front-end > JS Tutorial > Javascript method to convert Array and String to each other_javascript skills

Javascript method to convert Array and String to each other_javascript skills

WBOY
Release: 2016-05-16 15:24:18
Original
1149 people have browsed it

The example in this article describes the method of converting Array and String in Javascript. Share it with everyone for your reference, the details are as follows:

The Array class can be defined as follows:

Copy code The code is as follows:
var aValues ​​= new Array();

If you know the length of the array in advance, you can pass the length as a parameter
Copy code 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"

Copy after login

Method 2:

var aColors = new Array("red","green","blue"); // 和Array定义数组是等同的。
alert(aColors[0]); // output "red" too

Copy after login

(1) Array converted to string

The output of the above two array definition methods is the same, and there is a comma separator in the middle.

Copy code The code is as follows:
alert(aColors.toString()); // output "red,green,blue ";

(2) Convert string to Array

We found that when Array is converted into a string, there is an extra delimiter ',' between the arrays. Then when string is converted into an Array array, there must be a delimiter. It can be a comma or other delimiter.

var sColors = "red,green,blue";
var aColors = sColors.split(','); // 字符串就转换成Array数组了。

Copy after login

I hope this article will be helpful to everyone in JavaScript programming.

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template