Home > Web Front-end > JS Tutorial > body text

JS method to implement Array and String conversion

小云云
Release: 2017-12-01 09:31:20
Original
3131 people have browsed it

The Array function is a core component of PHP. No installation is required to use these functions. string is a string in programming languages. In this article, we will share with you the method of converting Array and String in Javascript. We hope it can help you.

The Array class can be defined as follows:

var aValues = new 
Array();
Copy after login

If you know the length of the array in advance, you can pass the length with parameters

var aValues ​​= new Array(20);

The following two definition methods 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) Convert Array to string

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

Copy the code The code is as follows:

alert(aColors.toString()); // output 
"red,green,blue";
Copy after login


(2) Convert string to Array

We found that Array is converted to string, and there are more between arrays 1 delimiter ',' , then to convert the string 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

The above content is how Javascript implements conversion between Array and String. I hope it will be helpful to everyone.

Related recommendations:

How to swap two variable values ​​in PHP (without using a third variable)

Traditional and Simplified Chinese interchange PHP function

PHP tutorial variable exchange

The above is the detailed content of JS method to implement Array and String conversion. For more information, please follow other related articles on the PHP Chinese website!

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