Reputation: 67
I need to print an array with indexes on the page. Console logs all indexes, but only last one prints out. In the code like this:
<body>
<p id="answer"></p>
<script>
let array = [11, 22, 33, 44];
for (let value of array) {
results = array.indexOf(value) + ':' + value;
console.log(results);
}
document.getElementById("answer").innerHTML=results
</script>
</body>
Upvotes: 1
Views: 36
Reputation: 386550
You need to add the part inside of the loop to innerHTML
.
let array = [11, 22, 33, 44],
result;
for (let value of array) {
results = array.indexOf(value) + ':' + value;
document.getElementById("answer").innerHTML += results + '<br>';
}
<p id="answer"></p>
A better version, could be to collect the wanted information and join a new string from the results.
let array = [11, 22, 33, 44];
document.getElementById("answer").innerHTML = array
.map((v, i) => [i, v].join(':'))
.join('<br>');
<p id="answer"></p>
Upvotes: 1