TypeScript 比较两个对象统计相同键值对数量,判断是否存在3个及以上匹配项
实现对比逻辑的核心思路
- 这类对象键值对比的场景,不需要把两个对象拆成独立的键数组、值数组做嵌套循环匹配,直接取共同键做单次遍历即可,冗余度极高的写法很容易因为顺序、数组长度不匹配出bug
- 你当前的需求本质是两个核心动作:第一遍历所有题目键,逐题比对标准答案和用户答案是否一致并计数;第二根据计数值判断是否达到通过阈值,输出对应提示
- 顺带提个容易忽略的基础语法问题:你写的两个对象字面量中,每个属性后缺少要求的逗号,直接运行会触发语法报错,需要先补上。
简化后的可运行实现
首先封装一个通用的对比方法,直接返回正确作答的题数:
function getCorrectAnswerCount(standardAnswer: Record<string, string>, userAnswer: Record<string, string>): number { // 过滤出两个对象共有的键,避免键缺失导致的取值报错 const sharedKeys = Object.keys(standardAnswer).filter(key => key in userAnswer); // 遍历共有键,累加值相等的计数 return sharedKeys.reduce((total, currentKey) => { return standardAnswer[currentKey] === userAnswer[currentKey] ? total + 1 : total; }, 0); }
结合你的业务判断逻辑调用即可:
// 补全逗号后的两个对象 const Questions = { five: "c", four: "c", one: "a", three: "a", two: "a" }; const Answers = { five: "a", four: "a", one: "a", three: "a", two: "a" }; // 拿到正确题数 const correctCount = getCorrectAnswerCount(Questions, Answers); // 根据阈值生成提示 let tip = ''; if (correctCount >= 3) { tip = '通过测验:你的正确作答数达到3道及以上'; } else { tip = `未通过测验:你本次仅答对${correctCount}道题,未达到3道的通过要求`; }
用你给出的两个对象跑下来的实际正确数是3(one、two、three三个题的答案匹配),刚好卡在通过阈值上。
你原有自定义方法的修正方向
你写的checkCorrectAnswers方法本来是想提取不匹配的题目,逻辑上没有本质错误,但写法太绕:完全不需要分别把两个对象的键、值抽成独立数组再做嵌套循环查找。直接基于共有键遍历一次,就能同时拿到正确数、错误题集合两类结果:
// 同时返回正确数和错误题集合的版本 function answerCheck(standardAnswer: Record<string, string>, userAnswer: Record<string, string>) { const sharedKeys = Object.keys(standardAnswer).filter(key => key in userAnswer); let correctCount = 0; const wrongItems: Record<string, string> = {}; sharedKeys.forEach(key => { if (standardAnswer[key] === userAnswer[key]) { correctCount++; } else { wrongItems[key] = standardAnswer[key]; } }); return { correctCount, wrongItems }; }
内容的提问来源于stack exchange,提问作者Miomir Dancevic
相关产品推荐
相关产品推荐

