1
var arr = [1, "one", 2, "two"];

How do you print an array inside html document element formatted as:

[1, "one", 2, "two"]
2
  • Have you tried maybe using someElement.innerHTML = [1, "one", 2, "two"]? Commented Jul 8, 2018 at 19:56
  • 2
    did you try JSON.stringify(array) Commented Jul 8, 2018 at 19:59

2 Answers 2

2

Using JSON.stringify(), for example yields this:

var arr = [1, "one", 2, "two"];

document.querySelector("#id").innerHTML = JSON.stringify(arr)
<p id="id"></p>

If you want the spaces behind the commas you need to build up the string for the element, like so:

var arr = [1, "one", 2, "two"];

let output = "[";

arr.forEach(e => output += JSON.stringify(e) + ", ");

output  = output.substring(0, output.length-2)

output += "]"

document.querySelector("#id").innerHTML = output
<p id="id"></p>

Sign up to request clarification or add additional context in comments.

1 Comment

The second example (the one that replaces the comma) may produce wrong results giving that there are strings in the array and that those strings may have commas in them.
2

Use:

JSON.stringify(array);

Example:

let arr = [1, 'a', '2', 'b'];

document.getElementById('p1').textContent = JSON.stringify(arr);
<p id="p1"></p>

4 Comments

Why aren't you using the tools Stackoverflow offers you to format your post?
It was my first post here, i wasnt sure how to use them. updated my answer :)
Welcome to SO! You can use runnable code snippetts for examples. Here is a list of all the things you can do to make your answer look better. Happy reading!
Thank you! I learned how to format my answer in a question about formatting code, amusing.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.