Home > Web Front-end > JS Tutorial > How to Convert a String with Commas to an Array in JavaScript?

How to Convert a String with Commas to an Array in JavaScript?

Barbara Streisand
Release: 2024-11-06 11:42:03
Original
386 people have browsed it

How to Convert a String with Commas to an Array in JavaScript?

Converting String with Commas to Array in JavaScript

Converting a string such as "0,1" to a JavaScript array can be challenging. Let's address the code example provided:

var string = "0,1";
var array = [string];
alert(array[0]);
Copy after login

In this scenario, 'alert(array[0])' displays "0,1". To obtain the desired result of an array, we need to convert the string.

Solution Using JSON.parse:

For simple array members, JSON.parse can be leveraged:

var array = JSON.parse("[" + string + "]");
Copy after login

This approach yields an array of numbers:

[0, 1]
Copy after login
Copy after login

Alternative Solution Using .split():

If you prefer to use .split(), you'll obtain an array of strings:

var array = string.split(",");
Copy after login
["0", "1"]
Copy after login

Considerations for Alternative Solution:

Note that .split() can't handle complex data types like undefined or functions. In such cases, eval() or a JavaScript parser is required.

To convert the split strings to numbers, you can utilize Array.prototype.map:

var array = string.split(",").map(Number);
Copy after login

This returns an array of numbers:

[0, 1]
Copy after login
Copy after login

To support Array.prototype.map in older browsers, consider shimming it or using a traditional loop.

The above is the detailed content of How to Convert a String with Commas to an Array in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!

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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template