【发布时间】:2019-07-12 05:43:51
【问题描述】:
我想显示来自 'pupils' 的所有学生数据,它是属于 School 类的对象数组。
我创建了一个新的学校类实例和一个 forEach 循环,该循环获取每个学生对象并使用document.getElementById().innerHTML 在段落文本中显示对象的每个属性。
class School {
constructor(name, level, pupils) {
this.name = name;
this.level = level;
this.pupils = pupils;
}
}
let pupils = [
{
name: 'John Doe',
age: 17,
grades: {
'English': 9,
'Maths': 9,
'Sociology': 'A*'
},
attendance: 45
},
{
name: 'Jane Doe',
age: 17,
grades: {
'English': 7,
'Maths': 6,
'Sociology': 'B'
},
attendance: 93
}
];
const myschool = new School('My School', 'high', pupils);
myschool.pupils.forEach(function(pupil) {
document.getElementById('pupils').innerHTML = `<h2>${pupil.name}
</h2><p>Age: ${pupil.age}</p><p>Attendance: ${pupil.attendance}
</p>`;
});
HTML:
<div id='pupils'>
</div>
我的代码正确地只显示了一个学生(Jane Doe)。它应该同时显示。
<div id='pupils'>
<p>
Jane Doe
Age: 17
Attendance: 93
</p>
</div>
【问题讨论】:
标签: javascript html arrays object ecmascript-6