JS数组查找:获取text含指定短语对象的id及报错解决
问题解决:找到包含指定短语的评论ID
错误原因
报错Cannot read properties of null (reading 'includes'),是因为数组中存在text字段为null、undefined或不存在的元素,直接调用includes会触发类型错误。
修正方案
方案1:使用可选链操作符(ES2020+)
可选链操作符?.会在左侧值为null/undefined时终止调用,避免报错:
const myArray = [ { "text": "Hello", "id": "11", "$type": "Comment" }, { "text": "Date of birth: 01-01-2022", "id": "22", "$type": "Comment" }, { "text": "lalala", "id": "33", "$type": "Comment" } ]; // 先过滤出text存在且包含指定短语的元素 let dateOfBirthComment = myArray.find(element => element.text?.includes('Date of birth')); // 处理未找到匹配项的情况 let dateOfBirthCommentId = dateOfBirthComment?.id || '未找到匹配的评论'; console.log(dateOfBirthCommentId); // 输出:22
方案2:兼容旧环境的写法
如果运行环境不支持可选链,可先判断text字段是否存在:
const myArray = [ { "text": "Hello", "id": "11", "$type": "Comment" }, { "text": "Date of birth: 01-01-2022", "id": "22", "$type": "Comment" }, { "text": "lalala", "id": "33", "$type": "Comment" } ]; let dateOfBirthComment = myArray.find(element => { // 先确保text存在,再判断是否包含指定短语 return element.text && element.text.includes('Date of birth'); }); // 处理未找到的情况 let dateOfBirthCommentId = dateOfBirthComment ? dateOfBirthComment.id : '未找到匹配的评论'; console.log(dateOfBirthCommentId); // 输出:22
关键说明
- 必须先确认
element.text存在且为字符串类型,再调用includes方法; - 额外判断
dateOfBirthComment是否存在,避免未找到匹配项时取id报错。
内容的提问来源于stack exchange,提问作者Alexander Aykhoff
相关产品推荐
相关产品推荐

