先来看两个场景:
场景1
我需要判断数组对象中的某个值是否存在进而去做其他事情:
let title;
if(data&&data.children&&data.children[0]&&data.children[0].title) {
title = data.children[0].title
}
场景2
我需要判断某个值是否有效进而去做其他事情
let isMan,text,person = {
name: 'zhangsan',
hasCount: 0,
isMan: false
};
if(person.hasCount || person.hasCount === 0) {
text = person.hasCount
} else {
text = '暂无数据'
}
上面两个场景我在开发中经常用到,后来在公众号得知js的新语法可选链"?."以及双问号"??"能使这两个场景操作变得简单。
优化如下
//场景1
let title = data?.children?.[0]?.title
//场景2
let {hasCount} = person;
text = hasCount ?? '暂无数据'
//除此之外,"??"还有其他应用场景
let a;
a ??= 6;
console.log(a); // 6
可选链的语法允许开发者访问嵌套得更深的对象属性,而不用担心属性是否真的存在。也就是说,如果可选链在挖掘过程遇到了null或undefined的值,就会通过短路(short-circuit)计算,返回undefined,而不会报错。
逻辑空分配运算符仅在空值或未定义(null or undefined)时才将值分配给a
那么,怎么在vue项目中使用呢?
首先,安装依赖:npm install --save-dev @babel/plugin-proposal-optional-chaining
npm install --save-dev @babel/plugin-proposal-nullish-coalescing-operator
其次,在项目的babel.config.js文件中添加配置如下
plugins: [
'@babel/plugin-proposal-optional-chaining',
'@babel/plugin-proposal-nullish-coalescing-operator'
]
最后,重启项目。
搞定。