首页 > 解决方案 > 如何在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;
  }
}

它需要两个参数:

它应该返回一个布尔值,表示学生是否通过了测验。

例如:

scoreQuiz(responses, 0.8);  //> false
scoreQuiz(responses, 0.75); //> true
scoreQuiz(responses, 0.7);  //> true

我得到了正确返回的真实,但由于某种原因它没有返回错误。
有人可以帮忙吗?

标签: javascript

解决方案


为了使您的代码正常工作,您必须使用以下注释对其进行更新:

// 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


推荐阅读