如何使用JavaScript Array.find时判断undefined并安全取值
安全获取Array.find匹配对象的属性值
我懂你的痛点——直接在find后面链式调用.value的话,一旦find没找到匹配项返回undefined,立刻就会抛出Cannot read properties of undefined的错误,对吧?你想要的是匹配到目标key时拿到对应的value,没匹配到就得到undefined,之后可以自己判断是否可用。
这里给你几种靠谱的解决方案:
方法1:先存匹配对象,再判断取值
最基础的兼容性写法,不管是新老JS环境都能用:
const t = 'abc'; const t1 = 'xyz'; const temp = [{key: "abc", value: "Value1"}]; // 先获取匹配的对象,找不到就是undefined const matchedItem = temp.find(check => check.key === t); // 安全获取value:存在则取值,否则返回undefined const targetValue = matchedItem ? matchedItem.value : undefined; console.log(targetValue); // 输出 'Value1' // 测试t1的情况 const matchedItem1 = temp.find(check => check.key === t1); const targetValue1 = matchedItem1 ? matchedItem1.value : undefined; console.log(targetValue1); // 输出 undefined
方法2:用可选链操作符(ES2020+),简洁又安全
如果你的项目支持ES2020及以上的语法,可选链?.是最优解——它会自动检查左边的值是否为null或undefined,是的话直接返回undefined,不会继续访问后续属性:
const t = 'abc'; const t1 = 'xyz'; const temp = [{key: "abc", value: "Value1"}]; const targetValue = temp.find(check => check.key === t)?.value; console.log(targetValue); // 输出 'Value1' const targetValue1 = temp.find(check => check.key === t1)?.value; console.log(targetValue1); // 输出 undefined
额外:搭配空值合并运算符设置默认值
要是你想在没匹配到的时候返回一个默认值,而不是undefined,可以结合空值合并运算符??一起用:
const targetValue1 = temp.find(check => check.key === t1)?.value ?? '默认值'; console.log(targetValue1); // 输出 '默认值'
这样不管匹配成功还是失败,都能安全拿到你想要的结果,不会触发报错~
内容的提问来源于stack exchange,提问作者user1015388




