将数组数组的字符串转换为数组的Javascript数组的优雅方法?
问题描述:
我有一个ajax请求,它返回这样的值列表:
I have an ajax request that returns a list of values like this:
"[-5, 5, 5], [-6, 15, 15], [7, 13, 12]"
我需要它是一个带有数字的javascript数组:
I need it to be a javascript array with numbers:
[[-5, 5, 5], [-6, 15, 15], [7, 13, 12]]
我试图用'|'替换'['和']'然后除以"|"并将foreach项除以','并将它们添加到数组中,但这完全不优雅.
I tried to replace the '[' and ']' for a '|' and then split by '|' and foreach item split by ',' and add them to an array, but this is not elegant at all.
你们有什么建议吗?
答
You can use JSON.parse()
to convert that string into an array, as long as you wrap it in some brackets manually first:
var value = "[-5, 5, 5], [-6, 15, 15], [7, 13, 12]";
var json = JSON.parse("[" + value + "]");
console.log(json);
我建议,如果可能,请更正服务器上的输出.
I would suggest correcting the output at the server if possible, though.