将逗号分隔的字符串转换为 JavaScript 数组
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11883187/
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
Convert comma separated string to a JavaScript array
提问by keyur ajmera
I have this string:
我有这个字符串:
"'California',51.2154,-95.2135464,'data'"
I want to convert it into a JavaScript array like this:
我想把它转换成这样的 JavaScript 数组:
var data = ['California',51.2154,-95.2135464,'data'];
How do I do this?
我该怎么做呢?
I don't have jQuery. And I don't want to use jQuery.
我没有 jQuery。而且我不想使用 jQuery。
回答by George D
Try:
尝试:
var initialString = "'California',51.2154,-95.2135464,'data'";
var dataArray = initialString .split(",");
回答by Christoph
Use the split function which is available for strings.
使用可用于字符串的 split 函数。
var ar = "'California',51.2154,-95.2135464,'data'".split(",");
and convert the numbers to actual numbers, not strings.
并将数字转换为实际数字,而不是字符串。
for (var i = ar.length;i--; ) {
var tmp = parseFloat(ar[i]);
ar[i] = (!isNaN(tmp)) ? tmp: ar[i].replace(/['"]/g,"");
}
Beware, this will fail if your string contains arrays/objects.
请注意,如果您的字符串包含数组/对象,这将失败。
回答by HBP
Since you format almost conforms to JSON syntax you could do the following :
由于您的格式几乎符合 JSON 语法,您可以执行以下操作:
var dataArray = JSON.parse ('[' + initialString.replace (/'/g, '"') + ']');
That is add '[' and ']' characters to be beginning and end and replace all "'' characters with '"'. than perform a JSON parse.
即添加 '[' 和 ']' 字符作为开头和结尾,并用 '"' 替换所有 "'' 字符。而不是执行 JSON 解析。