javascript存储for循环结果

标签 javascript for-loop

有没有办法将“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/

相关文章:

javascript - 我需要 Angular/Ionic 应用程序方面的帮助

javascript - javascript中以一定速度跟随鼠标光标的图像

java - Java 中的 For 循环和数组

javascript - 在数组原型(prototype)中循环

javascript - 为什么我没有成功地在第二个代码部分中获得嵌入的 "if"来完成其工作?

javascript - 单击链接时更改 div 中的内容

javascript - 如何根据内容、文本和子列设置网格列的宽度

python - 向量化嵌套的 for 循环 Python

c++ - 不同类型的for循环c++

c - 如何保持运行总计