Makis Mouzakitis
Makis Mouzakitis

Reputation: 55

Print array inside html document formatted as array and not a string

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

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

[1, "one", 2, "two"]

Upvotes: 1

Views: 370

Answers (2)

Sean Dvir
Sean Dvir

Reputation: 310

Use:

JSON.stringify(array);

Example:

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

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

Upvotes: 2

Luca Kiebel
Luca Kiebel

Reputation: 10096

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>

Upvotes: 2

Related Questions