Home >Web Front-end >JS Tutorial >How to Convert Comma-Delimited Strings to Arrays in JavaScript?

How to Convert Comma-Delimited Strings to Arrays in JavaScript?

DDD
DDDOriginal
2024-11-06 17:42:02451browse

How to Convert Comma-Delimited Strings to Arrays in JavaScript?

Converting Comma-Delimited Strings to Arrays in JavaScript

While attempting to convert a comma-separated string into a JavaScript array, you've noticed that the resulting array contains the entire string rather than the individual elements. To achieve the desired array format, consider the following solution:

Solution:

To convert a comma-separated string into an array of numbers, use JSON.parse as follows:

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

This approach returns an array of numbers:

[0, 1]

Alternatively, using .split() will result in an array of strings:

["0", "1"]

Limitations:

JSON.parse has limitations when handling data types. If you require values like undefined or functions, use eval() or a JavaScript parser.

Additional Notes:

If you prefer to use .split() and obtain an array of numbers, you can employ Array.prototype.map to convert string elements to numbers. For compatibility with IE8 and earlier, you may need to create a shim or use a traditional loop:

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

The above is the detailed content of How to Convert Comma-Delimited Strings to Arrays in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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