var arr = [1, "one", 2, "two"];
How do you print an array inside html document element formatted as:
[1, "one", 2, "two"]
ibrahim mahrir
31.8k5 gold badges50 silver badges78 bronze badges
asked Jul 8, 2018 at 19:53
Makis Mouzakitis
551 silver badge6 bronze badges
2 Answers 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>
answered Jul 8, 2018 at 20:02
Luca Kiebel
10.1k7 gold badges34 silver badges47 bronze badges
Sign up to request clarification or add additional context in comments.
1 Comment
ibrahim mahrir
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.
Use:
JSON.stringify(array);
Example:
let arr = [1, 'a', '2', 'b'];
document.getElementById('p1').textContent = JSON.stringify(arr);
<p id="p1"></p>
Luca Kiebel
10.1k7 gold badges34 silver badges47 bronze badges
4 Comments
Luca Kiebel
Why aren't you using the tools Stackoverflow offers you to format your post?
Sean Dvir
It was my first post here, i wasnt sure how to use them. updated my answer :)
ibrahim mahrir
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!
Sean Dvir
Thank you! I learned how to format my answer in a question about formatting code, amusing.
lang-js
someElement.innerHTML = [1, "one", 2, "two"]?JSON.stringify(array)