我正在使用XMLHttpRequest读取文本文件。其内容如下:
['01.html', '02.html', '03.html']
xhr.responseText
是一个字符串,我无法将其转换为数组,即使它的编写方式与数组完全相同。
特别是,JSON.parse
不起作用,因为这里的字符串使用单引号('...'
),而JSON语法只识别带双引号的字符串("..."
)。
答案 0 :(得分:1)
只是因为你坚持JSON.parse
。
这就是你如何做到的。基本上,就像你说的那样,重新格式化字符串数组并用一组"
双引号括住每个元素,然后解析它。
var test = "['01.html', '02.html', '03.html']".replace(/'/g, '"');
console.log(JSON.parse(test));