简体   繁体   English

如何使javascript将多维数组转换为字符串?

[英]How to make javascript turn a multidimensional array into a string?

I have a multidimensional array in javascript that I would like to be able to turn into a string while preserving brackets. 我在javascript中有一个多维数组,我希望能够在保留方括号的同时变成字符串。 I have taken a look at other questions such as javascript - Convert array to string while preserving brackets and the answers there didn't help me much. 我看过其他问题,例如javascript-在保留方括号的同时将数组转换为字符串,那里的答案对我没有太大帮助。

My array could look like the following: 我的数组如下所示:

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

When I print the array I see: 当我打印数组时,我看到:

0,0,1,1,1,0,0,4,1,0,1,5,0,1,1,3,1,1,0,6,0,1,0,2

The output that I am expecting is what the original array looks like. 我期望的输出是原始数组的样子。

I have also tried the following code: 我还尝试了以下代码:

alert("[[" + myArray.join("],[") + "]]");

This works for almost everything, I get an output of: 这几乎适用于所有情况,我得到的输出是:

[[0,0,1,1],[1,0,0,4],[1,0,1,5], ...

And I would like to see what the origional array looks like with the brackets. 我想看看带有方括号的原始数组是什么样的。 I would also like to stay away from JSON.stringify(); 我也想远离JSON.stringify(); and JSON.parse(); 和JSON.parse();

JSON.stringify() and JSON.parse() will do exactly what you ask for. JSON.stringify()JSON.parse()会完全满足您的要求。 Try it out: 试试看:

 var arr = [[[0,0,1],1],[[1,0,0],4],[[1,0,1],5], [[0,1,1],3],[[1,1,0],6],[[0,1,0],2]]; var str = JSON.stringify(arr); alert(str); var parsed = JSON.parse(str); alert(parsed); console.log(parsed); 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM