javascript - 将字符串转换为元组数组 [英] javascript -- converting string to array of tuples

查看:145
本文介绍了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]}`));

这篇关于javascript - 将字符串转换为元组数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆