转换为字符串,JavaScript时保留嵌套数组结构

时间:2019-09-01 03:33:25

标签: javascript arrays string multidimensional-array

当我创建一个嵌套数组时,说:

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的元素,测试元素是否为数组等之外,还有其他更聪明的方法吗?

2 个答案:

答案 0 :(得分:3)

您可以使用JSON.stringify并替换

 ^\[|\]$

enter image description here

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))

答案 1 :(得分:1)

或者可能使用生成器手动构建字符串:

 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("");
相关问题