javascript - 如何在js中计算分数测验?
问题描述
我有一个对象数组:
[
{
question: 'What is the phase where chromosomes line up in mitosis?',
response: 'Metaphase',
isCorrect: true,
isEssayQuestion: false
},
{
question: 'What anatomical structure connects the stomach to the mouth?',
response: 'Esophagus',
isCorrect: true,
isEssayQuestion: false
},
{
question: 'What are lysosomes?',
response: 'A lysosome is a membrane-bound organelle found in many animal cells. They are spherical vesicles that contain hydrolytic enzymes that can break down many kinds of biomolecules.',
isCorrect: true,
isEssayQuestion: true
},
{
question: 'True or False: Prostaglandins can only constrict blood vessels.',
response: 'True',
isCorrect: false,
isEssayQuestion: false
}
];
我写了一个名为scoreQuiz
:
function scoreQuiz(responses, score) {
var num=score;
if(num==score) {
return true;
}
else {
return false;
}
}
它需要两个参数:
responses
- 给定人的所有响应的数组,以及score
- 一个十进制数字,表示通过测验所需的最低分数。
它应该返回一个布尔值,表示学生是否通过了测验。
例如:
scoreQuiz(responses, 0.8); //> false
scoreQuiz(responses, 0.75); //> true
scoreQuiz(responses, 0.7); //> true
我得到了正确返回的真实,但由于某种原因它没有返回错误。
有人可以帮忙吗?
解决方案
为了使您的代码正常工作,您必须使用以下注释对其进行更新:
// changed score to minScoreToPass to be more descriptive.
function scoreQuiz(responses, minScoreToPass) {
// here I'm using reduce method to calculate the score for the responses.
const score = responses.reduce((val, item) => {
return item.isCorrect ? val += 1 : val;
}, 0)
// here you have to compare the score in decimal form so I divide by the total questions to get the percentage/decimal and compare to minScoreToPass
if (score/responses.length >= minScoreToPass) {
return true;
} else {
return false;
}
}
如果需要,请查看 reduce 方法:https ://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce
推荐阅读
- authentication - 使用 IdentityServer4 对 API 进行自定义 JWT 身份验证
- android-studio - getRawX() 和 getRawY() 以什么单位返回?
- python - 安装 pip install requests 和 pip install bs4
- swift - Swiftui 视图关闭后如何清理环境对象?
- python - xlwings 插件找不到 python 安装
- android - 检查服务器推送通知的服务
- azure - 不存在与模板匹配的 OData 路由 - 在 Azure intune 中添加 CorporateIdentifier
- c-preprocessor - 如何使用 C 预处理器查找 glibc 版本?
- javascript - 通过javascript将json转换为树数据
- java - JSTL:显示列表中的 N 个项目