以下是一个遍历一个包含对象数组的对象的示例代码:
let obj = {
name: 'John',
age: '30',
friends: [
{ name: 'Alice', age: '28' },
{ name: 'Bob', age: '32' },
{ name: 'Charlie', age: '27' }
]
};
// 遍历对象数组的方法之一是使用for...of循环
for (let friend of obj.friends) {
console.log(friend.name + ' is ' + friend.age + ' years old.');
}
// 遍历对象数组的方法之二是使用forEach方法
obj.friends.forEach(function(friend) {
console.log(friend.name + ' is ' + friend.age + ' years old.');
});
// 遍历对象数组的方法之三是使用map方法
let friendNames = obj.friends.map(function(friend) {
return friend.name;
});
console.log(friendNames);
运行以上代码会输出:
Alice is 28 years old.
Bob is 32 years old.
Charlie is 27 years old.
['Alice', 'Bob', 'Charlie']
以上代码示例中,我们首先定义了一个包含对象数组的对象。然后,使用for...of循环、forEach方法和map方法分别遍历了对象数组,输出了每个对象的属性值。