[英]Convert matrix in string format into Javascript array
I have an array containing arrays in HTML as a string我有一个包含 HTML 中的数组作为字符串的数组
<div id='foo'>['A', 'B', [['C', 1, 2]]]</div>
What I want我想要的是
var myArray = ['A', 'B', [['C', 1, 2]]];
I've been trying to grab it with something like $("#foo").text();
我一直在尝试用
$("#foo").text();
东西来抓取它$("#foo").text();
then convert it to a Javascript variable.然后将其转换为 Javascript 变量。 Normally I'd just use
data.split(',')
, however with the sub array, things get messed up.通常我只会使用
data.split(',')
,但是对于子数组,事情会变得一团糟。 I'd like to not use eval()
.我不想使用
eval()
。 How can I convert this string into a js array?如何将此字符串转换为 js 数组?
Replace the single quotes to double quotes, and use JSON.parse()
on the string to convert to an array:将单引号替换为双引号,并在字符串上使用
JSON.parse()
转换为数组:
const result = JSON.parse(document.querySelector('#foo') .innerText .replace(/'/g, '"')); console.log(result)
<div id='foo'>['A', 'B', [['C', 1, 2]]]</div>
var myArray = $('#foo').textContent
will get the values as a string and put in your variable.将获取作为字符串的值并放入您的变量中。 Do realize this does not convert it to Array.
请注意这不会将其转换为数组。 Do you really need it as array or as string?
你真的需要它作为数组或字符串吗?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.