[英]Transform string into array of arrays, Javascript
I have a string which looks like that: 我有一个看起来像这样的字符串:
[ [a,b,c],[a,b,c],[a,b,c] ]
I'd like to change it into an array of arrays. 我想将其更改为数组数组。 Do you know how can I do it?
你知道我该怎么办吗?
如果您的字符串是有效的JSON数组,则可以使用JSON.parse
:
var anArray = JSON.parse(arrayString)
If your string is actually like this (valid JSON): 如果您的字符串实际上是这样的(有效JSON):
var string = '[["a", "b", "c"], ["a", "b", "c"], ["a", "b", "c"]]';
then you can do 那你就可以
console.log(JSON.parse(string));
[["a", "b", "c"], ["a", "b", "c"], ["a", "b", "c"]]
[[“ a”,“ b”,“ c”],[“ a”,“ b”,“ c”],[“ a”,“ b”,“ c”]
With 用
var string = "[[a,b,c],[a,b,c],[a,b,c]]";
there is not much you can do as it isn't valid JSON, and a,b,c
aren't defined. 您不能做很多事情,因为它不是有效的JSON,并且没有定义
a,b,c
。 You will have to massage your "string" more to make it at least valid JSON. 您将不得不进一步按摩“字符串”,使其至少成为有效的JSON。
Well, you could try to split it on the "["-chars while ignoring the "]"-characters. 好吧,您可以尝试在“ [”字符上拆分它,而忽略“]”字符。
var str = "[[a,b,c],[a,b,c],[a,b,c]]"
var splitted = str.split("[");
var outerArray = [];
for(var i in splitted){
var token = splitted[i].replace(/]/g, "");
if(token.length > 0){
var innerArray = token.split(",");
if (innerArray.length > 0)
outerArray.push(innerArray);
}
}
This is definitly not elegant, and may be prone to errors, due to unhandled whitespaces or empty strings. 这肯定不是很优雅,并且由于未处理的空格或空字符串可能会导致错误。 But this may be a way you could go...
但这可能是您可以使用的方式...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.