js中的双问号和“?.“的含义和使用

总结:

 this.approveRecords[2].files[0].id 会报错 因为files:[],
所以写成this.approveRecords[2]?.files[0]?.id让它链不下去就好了

?? 表示:只有左侧的值为null或undefined的时候才使用右侧的值。

?. 表示:可选链操作符( ?. )允许读取位于连接对象链深处的属性的值,而不必明确验证链中的每 个引用是否有效。操作符的功能类似于 . 链式操作符,不同之处在于,在引用为空(null 或者 undefined) 的情况下不会引起错误,该表达式短路返回值

?.的个人理解 打个比方就是判断对象的某个属性是否存在,如果存在那么就返回整个属性的值,否则返回undefined

贴上自测的代码

const obj = {
name: 'ceshi',
detail: {
cat: 'huahua'
}
}
const name = obj.dog ?. name;
console.log(name) // undefined
因为obj不存在dog属性,所以查找dog下面的name根本没有所以返回undefined

const detail = obj.detail ?. cat;
console.log(detail)
查找obj下面detail的cat值,因为定义了,所以返回huahua

两者的结合使用

const cat = obj.detail ?. cat ?? 'default name'
console.log(cat) // huahua
这个时候存在detail然后去detail下查找cat属性,因为obj定义了cat所以返回huahua

const cat = obj.detail ?. name ?? 'default name'
console.log(cat)
上图含义是查找obj中detail属性下面name属性,但是对象中没有定义所以值是undefined,这个时候??左侧是undefied那么久使用右侧的数据所以最终返回default name
————————————————
原文链接:https://blog.csdn.net/szl199107101035/article/details/123839403

posted @ 2022-08-17 10:03  影思密达ing  阅读(3418)  评论(0编辑  收藏  举报