转换为字符串,JavaScript时保留嵌套数组结构 [英] Preserve Nested Array Structure When Converting to String, JavaScript
本文介绍了转换为字符串,JavaScript时保留嵌套数组结构的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
当我创建一个嵌套数组时,说:
When I create a nested array, say:
let x = [[0, 1], 2, [3, [4, 5]]];
并使用.toString()将其转换为字符串:
and convert it to a string with .toString():
x.toString();
-> "0,1,2,3,4,5"
它不保留数组的嵌套结构.我想得到类似的东西:
It doesn't preserve the nested structure of the array. I would like to get something like:
x.toString();
-> "[0,1],2,[3,[4,5]]"
除了遍历x的元素,测试元素是否为数组等之外,还有其他更聪明的方法吗?
Is there any smarter way of doing this other than looping through elements of x, testing if an element is an array etc.?
推荐答案
您可以使用JSON.stringify并替换
You can use JSON.stringify and replace
^\[|\]$
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时保留嵌套数组结构的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文