本文已参与「新人创作礼」活动,一起开启掘金创作之路。
“??“和“?.“都是es11新增的,用来进行空值和非空判断的运算符。
??:空值合并操作符
逻辑操作符,左侧为null和undefined时,才返回右侧的值。
与逻辑或操作符(
||)不同,逻辑或操作符会在左侧操作数为假值时返回右侧操作数。也就是说,如果使用||来为某些变量设置默认值,可能会遇到意料之外的行为。比如为假值(例如,''或0)时。
const sum = null ?? 12
console.log(sum); //12
const sum1 = 12 ?? 23
console.log(sum1); //12
const sum2 = undefined ?? 12
console.log(sum2); //12
const sum3 = 0 ?? 12
console.log(sum3); //0
const sum4 = '' ?? 12
console.log(sum4); //''
?. :可选链操作符
可以读取位于连接对象链深处属性的值,不必明确验证链中的每个引用是否有效。
功能类似于“.” 链式操作符,不同之处在于,在引用为空null 或者 undefined 的情况下不会引起错误,该表达式短路返回值是 undefined
与函数调用一起使用时,如果给定的函数不存在,则返回 undefined。
const fa = {
name: 'lming',
son: { name: 'lqq' }
}
const d = fa.d?.name
console.log(d) //输出undefined
可选链不可用于赋值
在vue中,template标签里使用可选链没有效果
使用方法:
1.获取一个对象更深层次的属性,即obj中的first属性下的second属性。
为了避免报错, 获取之前要判断first属性是否为null或者undefined,在获取second属性。
//使用“与”运算符。
let num = obj.first && obj.first.second
//使用?.可选链操作符
let num = obj.first?.second
2.可选链与函数调用
调用一个可能不存在的方法时,如果被调用的方法不存在,使用可选链可以使表达式自动返回undefined而不是抛出一个异常。
let result = someInterface.customMethod?.()
注:如果存在一个属性名且不是函数, 使用 ?. 仍然会产生一个 TypeError 异常 (x.y is not a function).
3.使用空值合并操作符
let customer = { name: "Carl", details: { age: 82 } }
let customerCity = customer?.city ?? "暗之城"
console.log(customerCity) // “暗之城”
4.短路计算
let a = null
let x = 0
let prop = a?.[x++]
console.log(x) // x 将不会被递增,依旧输出 0