How to implement mutual conversion between Array and String using Javascript _ javascript tips-js tutorial

Source: Internet
Author: User
Tags array to string
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.

Related Article

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.