自我教自己进行开发/ ES6并遇到一些问题,我已经尝试了一段时间。
我有学生的成绩和成绩的下限。尝试返回一个包含学生姓名,在该数组中的位置并将他们的分数转换为字母等级的数组。
我有switch语句,我只是在努力使用它来返回一个带有学生姓名,数组中的索引和字母等级的对象,以及如何使用const和fat arrow语法做到这一点。
任何帮助/指导将不胜感激。
谢谢
const scoreGrades = {
A: 100,
B: 90,
C: 80,
D: 70,
F: 60,
}
const gradeReport = [{
name: ‘Abby’,
mark: 20,
}, {
name: ‘Brian’,
mark: 100,
}, {
name: ‘Chella’,
mark: 60
}];
const studentResults = (gradeReport, scoreGrades) => {
function getstudentMarks (result) {
var mark = "";
switch(true) {
case mark < 60:
grade = "F";
break;
case mark < 70:
grade = "D";
break;
case mark < 80:
grade = "C";
break;
case mark < 90:
grade = "B";
break;
case mark <= 100:
grade = "A";
break;
}
return mark;
}
var i = 1;
while(i > 0 && <= 100){
console.log(i, 'should be', getstudentMarks(i));
i += 5;
}
}
答案 0 :(得分:1)
我建议您使用map
方法:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map。
此外,switch
不能那样工作。在最简单的实现中,您可以只使用一系列if
/ else if
。
这是一个可行的示例:
function getGrade(mark) {
if (mark < 60) {
return "E";
} else if (mark < 70) {
return "D";
} else if (mark < 80) {
return "C";
} else if (mark < 90) {
return "B";
} else {
return "A";
}
}
function getResults(scores) {
return scores.map((score, index) => ({
index: index,
name: score.name,
grade: getGrade(score.mark)
}));
}
const studentScores = [{
name: 'Abby',
mark: 20,
}, {
name: 'Brian',
mark: 100,
}, {
name: 'Chella',
mark: 60
}];
console.log(getResults(studentScores));
结果是:
[
{"index":0,"name":"Abby","grade":"E"},
{"index":1,"name":"Brian","grade":"A"},
{"index":2,"name":"Chella","grade":"D"}
]
答案 1 :(得分:0)
const scoreGrades = {
A: 100,
B: 90,
C: 80,
D: 70,
F: 60,
}
const gradeReport = [{
name: 'Abby',
mark: 20,
}, {
name: 'Brian',
mark: 100,
}, {
name: 'Chella',
mark: 60
}];
const getStudentResults = (gradeReport, scoreGrades) => {
let studentResults = []
gradeReport.forEach(student=>{
let grade;
if (student.mark >= 90) {
grade = 'A';
} else if (student.mark >= 80) {
grade = 'B';
} else if (student.mark >= 70) {
grade = 'C';
} else if (student.mark >= 60) {
grade = 'D';
} else {
grade = 'F'
}
studentResults.push({name:student.name, grade:grade});
})
return studentResults;
}
const studentResults = getStudentResults(gradeReport, scoreGrades);
console.log(studentResults);