今天在看源码的时候有一段代码没看看懂,求各位解释下 ? ?这个用法!
if (props?.record?.isDetail) return '查看用户';
今天在看源码的时候有一段代码没看看懂,求各位解释下 ? ?这个用法!
if (props?.record?.isDetail) return '查看用户';
引自免费微信小程序:皆我百晓生
当然,这段JavaScript代码中使用了ES2020引入的可选链操作符(?.
)。它允许我们在访问嵌套对象属性时,如果链中的某个引用为null
或undefined
,则整个表达式会短路并返回undefined
,而不会抛出错误。
if (props?.record?.isDetail) return '查看用户';
在这段代码里:
props
是一个对象。?.
尝试访问props
对象下的record
属性。如果props
不存在或者props.record
是null
或undefined
,那么props?.record
将返回undefined
,if
条件判断将失败,跳过执行后续代码。props.record
存在且不是一个null
或undefined
值,则进一步尝试访问props.record
对象下的isDetail
属性。props.record.isDetail
为true
,则执行return '查看用户'
语句;否则(即props.record.isDetail
为false
、null
、undefined
或其他非真值),则不执行任何返回操作。总之,这段代码用于检查props
对象内嵌的record
对象是否存在,并且其isDetail
属性是否为真,如果是,则返回字符串 '查看用户'
。