JavaScript中如何判断对象数组包含指定元素并访问对应属性?
原代码报错原因
searchEngines是数组类型,本身不存在name属性,直接读取searchEngines.name会得到undefined,对undefined调用includes方法会抛出类型错误,导致崩溃。
解决方案
1. 仅判断是否存在name为bing的元素
可以使用数组的some()方法,遍历数组判断是否有元素符合匹配条件:
const hasBing = searchEngines.some(item => item.name === 'bing'); console.log(hasBing); // 输出 true
2. 获取符合条件元素的索引和对应的link属性
可以使用数组的findIndex()方法,匹配到元素会返回对应索引,未匹配到返回-1,拿到索引后即可读取对应元素的属性:
// 获取匹配元素的索引 const targetIndex = searchEngines.findIndex(item => item.name === 'bing'); if (targetIndex !== -1) { console.log('元素索引:', targetIndex); // 输出 1 // 提取link属性 const targetLink = searchEngines[targetIndex].link; console.log(targetLink); // 输出 https://bing.com }
如果不需要索引只需要元素本身,也可以直接用find()方法:
const targetItem = searchEngines.find(item => item.name === 'bing'); if (targetItem) { console.log(targetItem.link); // 输出 https://bing.com }
内容的提问来源于stack exchange,提问作者Venkat Lohith Dasari
相关产品推荐
相关产品推荐

