可选链
在开发的时候通常会遇到这种情况,为了严谨我们的代码是这样的
var nickName = user.name && user.name.nickname;
var value= patient ? patient.value: undefine
再或者做判断
if (a && a.b && a.b.c) {
// Todo
}
当有了新语法以上可写成下面这样
var nickName = user.name?.nickname;
var value= patient.value? .value
if (a?.b?.c) {
// Todo
}
如果想在项目中使用此语法,需要babel7转译,插件选择@babel/plugin-proposal-optional-chaining
双问号
但在实际使用中,还是会有些不便,比如
const result = response?.settings?.n || 100
你的本意是如果 response 或者 response.settings 或者 response.settings.n 不存在(值为 null 或者 undefined)时,result 默认为 100。
但是上面代码在 n 为 0 的时候,也会让 result 变成 100,你实际上希望此时 result 为 0。
于是代码写成这样
const result = response?.settings?.n === undefined ? 100 : response?.settings?.n
或封装一下
const result = fetch(response?.settings?.n, 100)
所以双问号语法就来解决这个问题简化代码:
const result = response?.settings?.n ?? 100
?? 的意思是,如果 ?? 左边的值是 null 或者 undefined,那么就返回右边的值。
如果想在项目中使用此语法,需要babel7转译,插件选择@babel/plugin-proposal-nullish-coalescing-operator