[英]How to transform a string to an array
How to transform a string of this format '[11, 66]'
to an array?如何将这种格式的字符串
'[11, 66]'
转换为数组?
Array.isArray('[11, 66]')
return false since it's considered as string? Array.isArray('[11, 66]')
返回 false,因为它被视为字符串?
A good way to do this would be JSON.parse
.一个很好的方法是
JSON.parse
。
The JSON.parse() method parses a JSON string, constructing the JavaScript value or object described by the string.
JSON.parse() 方法解析 JSON 字符串,构造 JavaScript 值或 ZA86ZFF6891AC 字符串。
In your example:在您的示例中:
JSON.parse('[11, 66]')
Output: Output:
[11, 66]
If the string is a valid JSON string, then use JSON.parse
:如果字符串是有效的 JSON 字符串,则使用
JSON.parse
:
var array = JSON.parse(str);
Did you try to use JSON API?您是否尝试使用 JSON API?
JSON.parse(string); // turn a JSON string into a plain object (or an array as your example)
JSON.stringify(object); // turn an object (or an array) into JSON string
Also work for arrays!也适用于数组!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.