29

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

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
  • 2
    JSON.stringify(myArray) Did you want it formatted exactly like the original? Commented Mar 30, 2014 at 16:14
  • Thanks, formatting was a non-issue, but it's good to know (as you mention below) how to do so if it was Commented Mar 30, 2014 at 16:49

2 Answers 2

55

Use JSON.stringify():

var x = document.getElementById("result");
x.textContent = JSON.stringify( myArray );
Sign up to request clarification or add additional context in comments.

Comments

11

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

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 Comment

+1 This would be the way to go if he wanted it to be formatted just like the original syntax. Would just need to add a \n and a space. Probably faster too.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.