有没有办法将“for 循环”的结果存储在变量中?
例如,我想在 div 中显示两个名字 kevin 和 elsa。
我知道我可以做 john.friends[0].nom, john.friends[1].nom;
但是如果约翰有很多 friend ,那就很难了......
现在变量 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);
最佳答案
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
关于javascript存储for循环结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11455430/