use*_*149 3 javascript for-loop
有没有办法将“for循环”的结果存储在变量中?
例如,我想在 div 中显示两个名字 kevin 和 elsa。
我知道我可以做 john.friends[0].nom, john.friends[1].nom;
但如果约翰有很多朋友,那就很难了……
现在变量friendName给了我名字,我明白为什么但看不到解决方案......
谢谢 !
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);
Run Code Online (Sandbox Code Playgroud)
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
Run Code Online (Sandbox Code Playgroud)