Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

javascript storing for loop result

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);
like image 700
user1521149 Avatar asked Dec 05 '25 18:12

user1521149


1 Answers

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
like image 162
Daniel Li Avatar answered Dec 08 '25 07:12

Daniel Li



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!