我有一个默认设置,我定义了一堆变量,例如
let a="a", b="b", c="c", d="d", ...
我得到了一个多维数组 (as string)
即使用这些变量作为值,例如...
let matrixString = // (typeof matrixString === "string")
`[
[a, b, c, d, a],
[b, b, c, d, a],
[c, c, a, a, d]
]`
...我想使用"JSON.parse()"
解析这个字符串从字符串获取真实数组,但解析内部包含变量的字符串时似乎出现问题,因为我收到错误消息
JSON Parse error: Unexpected identifier "a"
请看我的例子:
/* ** default setup ** */
let a="a", b="b", c="c", d="d";
let matrix = [
[a, b, c, d, a],
[b, b, c, d, a],
[c, c, a, a, d]
]
console.log(matrix)
/* ** here is the issue ** */
let matrixAsString = `[
[a, b, c, d, a],
[b, b, c, d, a],
[c, c, a, a, d]
]`;
try {
let parsedMatrix = JSON.parse(matrixAsString)
console.log(parsedMatrix)
} catch(error) {
// error = 'JSON Parse error: Unexpected identifier "a"'
console.log(`Error: ${error}`)
}
如何在不使用映射字符串和添加 ""
等解决方法的情况下解决此问题之间或使用 "eval()"
。 有方法吗?
最佳答案
如果您首先没有要解析的 JSON
,则无法使用 JSON.parse()
。如果您需要更宽松的 JSON 定义来为您工作,请考虑类似 https://www.npmjs.com/package/really-relaxed-json 的内容。 .
但在这种情况下,您要查找的可能是模板文字:
/* ** default setup ** */
let a="1", b="2", c="3", d="4";
let matrix = [
[a, b, c, d, a],
[b, b, c, d, a],
[c, c, a, a, d]
]
console.log(matrix)
let matrixAsTemplateLiteral = `[
[${a}, ${b}, ${c}, ${d}, ${a}],
[${b}, ${b}, ${c}, ${d}, ${a}],
[${c}, ${c}, ${a}, ${a}, ${d}]
]`;
console.log(matrixAsTemplateLiteral);
关于javascript - 将包含变量名称的类似数组的字符串解析为数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52464105/