TypeScript获取对象值时触发TypeError,请问我哪里操作有误?
错误原因及修复方案
核心错误点
callList是单个对象,不能调用数组方法find()
你定义的callList是一个普通对象:
callList = { cd1: "00001", nm1: "17" }
而find()是数组的专属原型方法,对象本身没有这个方法。直接在对象上调用find()会导致该方法不存在,最终返回undefined,后续读取idx['cd1']自然会抛出Cannot read properties of undefined的错误。
- 未处理
find()返回undefined的边界情况
即使callList是数组,当find()找不到匹配项时也会返回undefined,此时直接访问其属性同样会触发报错。
针对性修复方案
方案1:如果callList就是单个对象(无需遍历)
直接判断属性匹配后取值即可,不需要用find():
const callList = { cd1: "00001", nm1: "17" }; const getFindbyNm = (cd: string) => { if (callList.nm1 === cd) { console.log(callList.cd1); // 输出 "00001" } else { console.log("未找到匹配项"); } }; getFindbyNm('17');
方案2:如果callList应该是数组(需遍历多个对象)
先修正callList为数组格式,再在调用find()后判断返回值是否存在:
// 修正为数组,存储多个对象 const callList = [ { cd1: "00001", nm1: "17" }, { cd1: "00002", nm1: "18" } ]; const getFindbyNm = (cd: string) => { const targetItem = callList.find(e => e.nm1 === cd); // 先判断是否找到匹配项 if (targetItem) { console.log(targetItem.cd1); // 找到时输出对应cd1 } else { console.log("未找到匹配的nm1"); } }; getFindbyNm('17'); // 输出 "00001"
内容的提问来源于stack exchange,提问作者tatsuya
相关产品推荐
相关产品推荐

