简体   繁体   中英

How to Convert Array-like String to Array

I have a string that looks like an array: "[918,919]" . I would like to convert it to an array, is there an easier way to do this than to split and check if it is a number? Thanks

使用JSON.parse

var myArray = JSON.parse("[918,919]");

You can get rid of the brackets at the beginning and the end, then use:

str.split(",")

which will return an array split by the comma character.

EDIT

var temp = new Array();
temp = "[918,919]".slice( 1, -1).split(",");
for (a in temp ) {
temp[a] = parseInt(temp[a]);
}

If you use JSON.parse the string must have " and not ' otherwise the code will fail.

for example:

let my_safe_string = "['foo','bar',123]";
let myArray = JSON.parse(my_safe_string)

the code will fail with

Uncaught SyntaxError: Unexpected token ' in JSON at position 1

instead if you use " all will work

let my_safe_string = "["foo","bar",123]";
let myArray = JSON.parse(my_safe_string);

so you have two possibility to cast string array like to array:

  • Replace ' with " my_safe_string.replace("'",'"'); and after do JSON.parse
  • If you are extremely sure that your string contain only string array you can use eval:

example:

let myArray = eval(my_safe_string );

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