我该如何编写一个带有两个参数(数组responses
和string
)的函数,并且对于isEssayQuestion
是正确的,比较string
参数作为response
键值的参数,如果它们与任何人匹配,则返回true
,如果与任何人都不匹配,则返回false
。
const responses = [
{
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
}
];
// example
checkForPlagiarism(responses, 'spherical vesicles that contain hydrolytic enzymes'); //> true
checkForPlagiarism(responses, 'this string does not appear in the responses'); //> false
// my code
function checkForPlagiarism(test, answerKey) {
for (let i = 0; i < test.length; i++) {
let question = test[i];
if (question.isEssayQuestion) {
let response = question.response;
return response.includes(answerKey);
}
}
}
答案 0 :(得分:0)
您不需要遍历对象,因为给定的响应本身就是数组。
除了return
语句之外,您所做的一切对我来说似乎还不错。
因此,请将您的return语句添加到字符串匹配逻辑的if
中。
function checkForPlagiarism(test, answerKey) {
for (let i = 0; i < test.length; i++) {
let question = test[i];
if (question.isEssayQuestion) {
let response = question.response;
if (response.includes(answerKey)) return true;
}
}
return false
}
答案 1 :(得分:0)
您的代码已经返回了正确的值(如果找到匹配项,则返回true;如果未找到匹配项,则返回false),如果未找到匹配项,则只需在for循环后添加return false即可(没有isEssayQuestion:true)。 对您的函数调用返回的值进行console.log()检出。
示例:
console.log(checkForPlagiarism(响应,“包含水解酶的球形囊泡”)) console.log(checkForPlagiarism(响应,“此字符串未出现在响应中”))