2 回答
TA贡献1866条经验 获得超5个赞
您可以通过以下方式对值进行平均:
const avg = (arr) => arr.reduce((acc, val) => acc + val, 0) / arr.length;
您可以通过以下方式调用上面的函数:
avg(student.grades.map(grade => parseInt(grade, 10)));
我还建议使用模板文字来构建输出 HTML。
演示
const apiInfo = $('.info');
const avg = (arr) => arr.reduce((acc, val) => acc + val, 0) / arr.length;
const renderStudentInfo = (student, $target) => {
const fullName = student.firstName + ' ' + student.lastName,
average = avg(student.grades.map(grade => parseInt(grade, 10)));
$target.append($(`
<div class="infoB">
<img class="pPic float-left m-3"
src="${student.pic}" alt="profile pic" />
<h4 class="title">${fullName}</h4>
<p class="mb-1 stats">Email: ${student.email}</p>
<p class="mb-1 stats">Company: ${student.company}</p>
<p class="mb-1 stats">Skill: ${student.skill}</p>
<p class="mb-1 stats">Average: ${average.toFixed(2)}%</p>
</div>
`));
};
const init = () => {
$.ajax({
url: 'https://api.hatchways.io/assessment/students',
method: 'GET',
}).then(({ students }) => {
students.forEach((student) => {
if (student.id.includes('')) {
renderStudentInfo(student, apiInfo);
}
});
});
}
init();
.infoB {
margin-bottom: 1em;
}
.infoB .title {
font-weight: bold;
}
.infoB .mb-1.stats {
color: #444;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment.min.js"></script>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css" />
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css" />
<div class="container">
<div class="info card scroll shadow p-3 mb-5 bg-white rounded"></div>
</div>
TA贡献1872条经验 获得超3个赞
您没有为地图提供正确的回调函数。尝试将该行更改为此
let x = sGrades.map((v) => `${parseInt(v)}%`)
但这将返回一个字符串数组。
添加回答
举报