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
Release: 2024-11-06 14:16:02
Original
1039 people have browsed it

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]);
Copy after login

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 + "]");
Copy after login

This will give you the expected result:

[0, 1]
Copy after login
Copy after login

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

["0", "1"]
Copy after login

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);
Copy after login

This will again give you the desired result:

[0, 1]
Copy after login
Copy after login

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!

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