Is there a way to store the result of the 'for loop' in a variable?
I want to display the two name kevin and elsa in a div for example.
I know i can do john.friends[0].nom, john.friends[1].nom;
but if John has many friends, it will be difficult...
Now the variable friendName gives me just name, I understand why but can't see the solution...
Thanks !
function Person(name, age, friends) {
this.name = name;
this.age = age;
this.friends = friends;
};
var john = new Person('john', 28, [new Person('elsa', 29, []), new Person('kevin', 31, [])]);
for (var i = 0; i < john.friends.length; i++) {
var friendName = john.friends[i].name;
}
alert(friendName);
var friendNames = []; // store their names within a local array
for(var i = 0; i < john.friends.length; i++){
friendNames.push(john.friends[i].name);
}
console.log(friendNames); // log to the browser (readability) instead of alert
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