当我创建一个嵌套数组时,说:
let x = [[0, 1], 2, [3, [4, 5]]];
并使用 .toString() 将其转换为字符串:
x.toString();
-> "0,1,2,3,4,5"
它不保留数组的嵌套结构。我想得到类似的东西:
x.toString();
-> "[0,1],2,[3,[4,5]]"
除了遍历 x 的元素、测试元素是否为数组等之外,还有更聪明的方法吗?
最佳答案
您可以使用 JSON.stringify 和替换
^\[|\]$
let x = [[0, 1], 2, [3, [4, 5]]];
let final = JSON.stringify(x)
// with regex
console.log(final.replace(/^\[|\]$/g,''))
// without regex
console.log(final.slice(1, -1))
关于javascript - 转换为字符串时保留嵌套数组结构,JavaScript,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57743009/