javascript storing for loop result
Solution 1
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
Solution 2
var friendNames = []; // create array to hold friend names
for(var i=0; i < john.friends.length; i++){
friendNames.push(john.friends[i].name); // add friend's name to the array
}
console.log(friendNames); // an array containing all of John's friends' names.
Solution 3
You probably want an array of names (list of all the names). Declare friendName = new Array()
and friendName.push(john.friends[i].name);
var friendName = new Array();
for (var i = 0; i < john.friends.length; i++) {
friendName.push(john.friends[i].name);
//or friendName[i] = john.friends[i].name;
}
//friendName is now an array of names. Use it as you need (the last line is useful for debugging)
for (i = 0; i < friendName.length; i++) alert(friendName[i]);
The problem with your old code was that each iteration of the loop would reassign friendName. When i = 0
, 'elsa' was assigned to friendName. When i = 1
, 'kevin' was reassigned to friendName.
Furthermore, javascript does not have block scoping; it would be like calling var friendName = 'elsa'; var friendName = 'kevin';
. Won't crap out the javascript engine, but just watch out for that. Better to declare friendName as an array above the loop as others and I have mentioned.
Solution 4
Since your friends
variable is an array, you can just use some of the methods available to you on that type:
var friendString = john.friends.map(function(f) { return f.name; }).join(' ');
In the above example, the map method maps the friends to just their names and then the join method will produce a space separated string of all johns friends.
user1521149
Updated on June 09, 2022Comments
-
user1521149 almost 2 years
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);