问题
When I create a nested array, say:
let x = [[0, 1], 2, [3, [4, 5]]];
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]]"
Is there any smarter way of doing this other than looping through elements of x, testing if an element is an array etc.?
回答1:
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))
回答2:
Or possibly use a generator to build up a string manually:
function* asNested(array) {
for(const el of array)
if(Array.isArray(el)) {
yield "[";
yield* asNested(el);
yield "]";
} else yield el.toString();
}
const result = [...asNested([[1, 2], [3, 4]])].join("");
来源:https://stackoverflow.com/questions/57743009/preserve-nested-array-structure-when-converting-to-string-javascript