简体   繁体   中英

How to transform a string to an array

How to transform a string of this format '[11, 66]' to an array?

Array.isArray('[11, 66]') return false since it's considered as string?

A good way to do this would be JSON.parse .

The JSON.parse() method parses a JSON string, constructing the JavaScript value or object described by the string.

In your example:

JSON.parse('[11, 66]')

Output:

[11, 66]

If the string is a valid JSON string, then use JSON.parse :

var array = JSON.parse(str);

Did you try to use 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!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM