Javascript 如何将逗号分隔的字符串转换为数组?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14288727/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 16:17:01  来源:igfitidea点击:

How to convert string separated by commas to array?

javascript

提问by Mindaugas Jakubauskas

Possible Duplicate:
Convert JS object to JSON string
Store comma separate values into array

可能的重复:
将 JS 对象转换为 JSON 字符串将
逗号分隔的值存储到数组中

I have a string containing values separated with commas:

我有一个包含用逗号分隔的值的字符串:

"1,4,5,11,58,96"

How could I turn it into an object? I need something like this

我怎么能把它变成一个对象?我需要这样的东西

["1","4","5","11","58","96"]

回答by joeltine

This will convert it into an array (which is the JSON representation you specified):

这会将其转换为一个数组(这是您指定的 JSON 表示):

var array = myString.split(',');

If you need the string version:

如果您需要字符串版本:

var string = JSON.stringify(array);

回答by kevin

make it an array

使它成为一个数组

var array = myString.split(',');

回答by tiffon

In JSON, numbers don't need double quotes, so you could just append [and ]to either end of the string, resulting in the string "[1,4,5,11,58,96]"and you will have a JSON Array of numbers.

在 JSON 中,数字不需要双引号,因此您可以将[和附加]到字符串的任一端,从而生成字符串"[1,4,5,11,58,96]",您将拥有一个 JSON 数字数组。