0

I'm looking for a way to list each firstname from the below loop. Currently it loops through each firstname stoping at the last which is Jack and only displaying that. I want it to display all of them like: John, Jane, Joe

var person = [{firstName:"John"}, {firstName:"Jane"}, {firstName:"Jack"}]; for (var i = 0; i < person.length; i++) { document.getElementById("demo").innerHTML = person[i].firstName; } 

Can anyone advise on how I would do this?

3 Answers 3

1

The problem is that your are overwriting the innerHTML value, instead that you need to append your values to innerHTML property using '+':

var person = [{firstName:"John"}, {firstName:"Jane"}, {firstName:"Jack"}]; var demo = document.getElementById("demo"); for (var i = 0, len = person.length; i < len; i++) { demo.innerHTML += person[i].firstName + ' '; } 

Check out this codepen. I have add some modifications to make the code more performant.

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

Comments

0

Please take a look at this code:

var person = [{firstName:"John"}, {firstName:"Jane"}, {firstName:"Jack"}], html = ""; for (var i = 0; i < person.length; i++) { html += person[i].firstName; } document.getElementById("demo").innerHTML = html; 

You are overwriting each time with the innerHTML because you are not using '+='. I like to create a string beforehand and set it to nothing. Then you can add everything to that and only need to call innerHTML once.

Hope this helps!

Comments

0

here's another way to do it using a more functional style

"use strict"; var people = [{firstName:"John"}, {firstName:"Jane"}, {firstName:"Jack"}]; var node = document.getElementById('demo'); node.innerHTML = people.map(function(person){ return person.firstName; }).join(', ');
#demo { padding: 1em; background-color: #def; border: 1px solid gray }
<div id="demo"></div>

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.