Preserve Nested Array Structure When Converting to String, JavaScript

狂风中的少年 提交于 2021-02-05 07:45:06

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!