将数组转换为字符串,同时保留括号

时间:2021-06-26 21:45:17

I have a multidimensional array that looks like this:

一个多维数组是这样的

var myArray =[[1,2,3,4,5], 
              [1,2,3,4,5], 
              [1,2,3,4,5], 
              [1,2,3,4,5]];

I wish to put its contents in a div (so that one can easily copy and paste).

我想把它的内容放在一个div中(这样可以很容易地复制和粘贴)。

However, when I do

然而,当我做的

var x = document.getElementById("result");
x.textContent = myArray;

I just get

我刚刚得到

1,2,3,4,5,1,2,3,4,5,1,2,3,4,5,1,2,3,4,5

2 个解决方案

#1


21  

Use JSON.stringify():

使用JSON.stringify():

var x = document.getElementById("result");
x.textContent = JSON.stringify( myArray );

#2


4  

You can either use JSON.stringify or custom joining like this

您可以使用JSON。像这样的弦化或自定义连接

console.log("[[" + myArray.join("],[") + "]]");
# [[1,2,3,4,5],[1,2,3,4,5],[1,2,3,4,5],[1,2,3,4,5]]
console.log(JSON.stringify(myArray));
# [[1,2,3,4,5],[1,2,3,4,5],[1,2,3,4,5],[1,2,3,4,5]]

#1


21  

Use JSON.stringify():

使用JSON.stringify():

var x = document.getElementById("result");
x.textContent = JSON.stringify( myArray );

#2


4  

You can either use JSON.stringify or custom joining like this

您可以使用JSON。像这样的弦化或自定义连接

console.log("[[" + myArray.join("],[") + "]]");
# [[1,2,3,4,5],[1,2,3,4,5],[1,2,3,4,5],[1,2,3,4,5]]
console.log(JSON.stringify(myArray));
# [[1,2,3,4,5],[1,2,3,4,5],[1,2,3,4,5],[1,2,3,4,5]]