gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 09:12:13 25 4
gpt4 key购买 nike

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

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 和替换

 ^\[|\]$

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

关于javascript - 转换为字符串时保留嵌套数组结构,JavaScript,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57743009/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com