I am wanting to create an array of objects and display a specific list of properties when certain conditions are met.
The following code does what I want when I print it to the console or use document.write.
var people = [{
firstName: 'John',
lastName: 'Doe',
age: 23,
},{
firstName: 'Jane',
lastName: 'Doe',
age: 53,
}]
for(i = 0; i < people.length; i++){
if(people[i].age < 65){
document.write(people[i].firstName + ' ' +
people[i].lastName + ' has printed to document. <br>');
}
}
But when I go to run the code in the browser, using document.getElementById, only the last item is displaying.
for(i = 0; i < people.length; i++){
if(people[i].age < 65){
result = 'Only ' + people[i].firstName + ' ' +
people[i].lastName + ' is printed to document. Why?';
}
}
document.getElementById('names').innerHTML = result;
Could someone explain to me why all items appear using document.write?
While only the last item appears when using document.getElementById?
The issue is in this line:
result = 'Only ' + people[i].firstName + ' ' +
people[i].lastName + ' is printed to document. Why?';
Because you're assigning the message string to result variable. Since you are in a loop, the result variable will just hold the last value.
You have to concat the message to result variable.
for(i = 0; i < people.length; i++){
if(people[i].age < 65){
result += 'Only ' + people[i].firstName + ' ' +
people[i].lastName + ' is printed to document. Why?';
}
}
Also, you can use string templates for formatting the message.
result += `Only ${people[i].firstName} ${people[i].lastName} is printed to document. Why?`;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With