Home >Web Front-end >JS Tutorial >How to Convert a String with Commas into a JavaScript Array of Numbers?

How to Convert a String with Commas into a JavaScript Array of Numbers?

Patricia Arquette
Patricia ArquetteOriginal
2024-11-06 14:16:021057browse

How to Convert a String with Commas into a JavaScript Array of Numbers?

How to Convert a String with Commas into a JavaScript Array

The code:

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

shows a problem when trying to convert a string with commas into a JavaScript array. The alert shows "0,1" instead of "0" as desired.

To resolve this, you can use JSON.parse to convert the string into an array of numbers:

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

This will give you the expected result:

[0, 1]

Note that using .split() will result in an array of strings:

["0", "1"]

JSON.parse has limitations regarding supported data types. If you need to work with undefined values or functions, you may need to consider using eval() or a JavaScript parser.

For more flexibility, you can also use .split() with Array.prototype.map to convert the strings to numbers:

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

This will again give you the desired result:

[0, 1]

Keep in mind that this approach requires a shim for IE8 and lower versions, or you can use a traditional loop instead of Array.prototype.map.

The above is the detailed content of How to Convert a String with Commas into a JavaScript Array of Numbers?. 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