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" />
<link rel="stylesheet" />
<div class="container">
? <div class="info card scroll shadow p-3 mb-5 bg-white rounded"></div>
</div>

TA貢獻1872條經驗 獲得超4個贊
您沒有為地圖提供正確的回調函數。嘗試將該行更改為此
let x = sGrades.map((v) => `${parseInt(v)}%`)
但這將返回一個字符串數組。
添加回答
舉報