javascript - 将字符串转换为元组数组
我有一个我要转换成数组的字符串
I have a string that I want to convert into array
[(6,11),(12,17),( 18,20)]
.split()
不起作用(或者至少我不知道如何分隔单词)和JSON.parse总是用解决掉#ScaxaxError:意外的令牌
.split()
wouldn't work (or at least I don't know how to separate the words) and JSON.parse always craps out with Uncaught SyntaxError: Unexpected token
我正在这样转换: JSON.parse(THAT_GIVEN_LIST)
我在做什么错误?如何将这个字符串变成一个很好的列表[(6,11),(12,17),(18,20)]
Am I doing something wrong? How do I make this string into a nice list of [(6, 11), (12, 17), (18, 20)]
您使用的括号在语法上对JSON不正确。你提出他们的意思是定义一个元组。但是,元组不是JSON原语。如果你想拥有这样的嵌套结构,最好的办法就是使用嵌套数组:
The parentheses that you are using are not syntactically correct for JSON. You pose that they mean to define a tuple. However, tuples are not JSON primitives. If you want to have nested structures like this, your best bet will be to use nested arrays:
const a = "[[6, 11], [12, 17], [18, 20]]";
const aa = JSON.parse(a);
console.log(aa);
aa.forEach(i => console.log(`first: ${i[0]}, second: ${i[1]}`));