【问题标题】:How to keep the array 'structure' inside a string in JavaScript [duplicate]如何在JavaScript中将数组“结构”保存在字符串中[重复]
【发布时间】:2020-07-05 15:18:54
【问题描述】:

我的问题是,如果我在 javascript 中有一个数组,假设:

let x = [1, 2, 3, [4, 5, 6]]

我想将它转换成如下所示的字符串:y = "[1, 2, 3, [4, 5, 6]]",我该怎么做? 我试过这些东西:

let a = x.toString();
let b = y.toLocaleString();
let c = new String(x);

但问题是,它们看起来都是这样的:

"1, 2, 3, 4, 5, 6"

因此,它完全删除了“[]”。 我怎样才能像这样将数组保留在字符串中:

"[1, 2, 3, [4, 5, 6]]"

与 []

【问题讨论】:

  • JSON.stringify(x) 将产生"[1,2,3,[4,5,6]]"。其他方法也不包括逗号后的空格。

标签: javascript arrays string


【解决方案1】:

这有帮助吗?

 let y = [1, 2, 3, [4, 5, 6]];
 

 var x = JSON.stringify(y);
 
 console.log(typeof(x));
 
 console.log(JSON.stringify(y));

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-04-18
    • 2019-10-11
    • 1970-01-01
    • 2019-01-05
    • 1970-01-01
    • 2021-07-12
    • 2014-10-25
    • 1970-01-01
    相关资源
    最近更新 更多