Javascript 给定数组,编写一个函数,返回数组中与该问题匹配的项
我需要编写一个函数findAnswersanswers,它返回数组中与该问题匹配的项。如果没有学生的答案与问题匹配,则返回undefined;如果有多个学生的答案与问题匹配,则返回数组中的第一个答案 示例输出:Javascript 给定数组,编写一个函数,返回数组中与该问题匹配的项,javascript,arrays,Javascript,Arrays,我需要编写一个函数findAnswersanswers,它返回数组中与该问题匹配的项。如果没有学生的答案与问题匹配,则返回undefined;如果有多个学生的答案与问题匹配,则返回数组中的第一个答案 示例输出: findAnswer(answers, "True or False: Prostaglandins can only constrict blood vessels."); /*=> { question: 'True or False: Pros
findAnswer(answers, "True or False: Prostaglandins can only constrict blood vessels."); /*=>
{
question: 'True or False: Prostaglandins can only constrict blood vessels.',
response: 'True',
isCorrect: false,
isEssayQuestion: false
}
*/
给定数组:
let answers = [
{
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
}
];
到目前为止,我所拥有的:
function findAnswer(answers, question) {
let result = {};
for (let i = 0; i < answers.length; i++) {
let studentAnswers = answers[i];
if (studentAnswers === answers) {
result[answers[i].question]
}
}
return result;
}
我知道代码很糟糕,我只是不知道如何返回匹配响应的数组…当您想在通过测试的数组中查找元素时,使用的合适方法是.find,如果找不到匹配项,它将返回undefined:
const findAnswer = (answers, question) => answers.find(
answer => answer.question === question
);
让答案=[
{
问题:“染色体在有丝分裂中排列的阶段是什么?”,
答复:“中期”,
是正确的,
问题:错
},
{
问题:“什么样的解剖结构连接着胃和嘴?”,
回应:"食道",,
是正确的,
问题:错
},
{
问题:“什么是溶酶体?”,
回应:“溶酶体是一种膜结合的细胞器,存在于许多动物细胞中。它们是球形囊泡,含有水解酶,可以分解多种生物分子。”,
是正确的,
问题:是吗
},
{
问题:“对还是错:前列腺素只能收缩血管。”,
回答:‘正确’,
I正确:错误,
问题:错
}
];
const findAnswer=答案,question=>answers.find
答案=>答案。问题===问题
;
控制台。Logfindanswerwers,对还是错:前列腺素只能收缩血管。;啊,这非常有帮助。非常感谢你!