其他分享
首页 > 其他分享> > js中“??“和“?.“怎么用?

js中“??“和“?.“怎么用?

作者:互联网

??:空值合并操作符
逻辑操作符,左侧为null和undefined时,才返回右侧的数

const sum = null ?? 12
console.log(sum);
//输出12

const sum1 = 12 ?? 23
console.log(sum1);
//输出12

const sum2 = undefined ?? 12
console.log(sum2);
//输出12

?. :可选链操作符
可以读取位于连接对象链深处属性的值,不必明确验证链中的每个引用是否有效
功能类似于“.” 链式操作符,不同之处在于,在引用为空null 或者 undefined 的情况下不会引起错误,该表达式短路返回值是 undefined
与函数调用一起使用时,如果给定的函数不存在,则返回 undefined。

const fa = {
name: 'lming',
son: {
name: 'lqq'
}
};
const duc = fa.duc?.name;
console.log(duc);
//输出undefined

使用:
1.获取一个对象更深层次的属性,即obj中的first属性下的second属性。
为了避免报错, 获取之前要判断first属性是否为null或者undefined,在获取second属性
使用“与”运算符

let num = obj.first && obj.first.second;

使用?.可选链操作符

let num = obj.first?.second;

可选链与函数调用
调用一个可能不存在的方法时,如果被调用的方法不存在,使用可选链可以使表达式自动返回undefined而不是抛出一个异常

let result = someInterface.customMethod?.();

注:如果存在一个属性名且不是函数, 使用 ?. 仍然会产生一个 TypeError 异常 (x.y is not a function).

使用空值合并操作符
let customer = {
name: "Carl",
details: { age: 82 }
};
let customerCity = customer?.city ?? "暗之城";
console.log(customerCity); // “暗之城”

短路计算
let a = null;
let x = 0;
let prop = a?.[x++];
console.log(x); // x 将不会被递增,依旧输出 0

标签:怎么,null,log,js,let,操作符,first,undefined
来源: https://www.cnblogs.com/houxianzhou/p/16404560.html