JavaScript 中??和?.的使用
空值合并操作符【??】 是一个逻辑操作符
- 只有当左侧为null和undefined时,才会返回右侧的数,否则返回左侧操作数
const strUndefined = undefined
console.log(strUndefined ?? '中'); // 中
const strNull = null
console.log(strNull ?? '中'); // 中
const strNumber0 = 0
console.log(strNumber0 ?? '中'); // 0
const strNumber = 1
console.log(strNumber ?? '中'); // 1
const strNumberNaN = NaN
console.log(strNumberNaN ?? '中'); // NaN
const strBooleanTrue = true
console.log(strBooleanTrue ?? '中'); // true
const strBooleanFalse = false
console.log(strBooleanFalse ?? '中'); // false
const str = ""
console.log(str ?? '中'); // ""
const strString = "国"
console.log(strString ?? '中'); // 国
const strArr = []
console.log(strArr ?? '中'); // []
const strArray = [1, 2]
console.log(strArray ?? '中'); // [1, 2]
const strObj = {}
console.log(strObj ?? '中'); // {}
const strObject = { name: '张三'}
console.log(strObject ?? '中'); // { name: '张三'}
可选链操作符【?.】
- 可选链操作符( ?. )允许读取位于连接对象链深处的属性的值,而不必明确验证链中的每个引用是否有效
- ?. 操作符的功能类似于 . 链式操作符,不同之处在于,在引用为空 (null 或者 undefined) 的情况下不会引起错误,该表达式短路返回值
语法:obj?.prop obj?.[expr] arr?.[index] func?.(args)
// 实例
const aa = {
name: 'Alice',
cat: {
name: 'Dinah'
}
};
const aaa = aa.dog?.name;
console.log(aaa);
// expected output: undefined
console.log(aa.fun?.());
// expected output: undefined
// 函数调用:
let result = someInterface.customMethod?.();
//如果希望允许 someInterface 也为 null 或者 undefined ,那么你需要像这样写 someInterface?.customMethod?.()
//可选链与表达式:
let nestedProp = obj?.['prop' + 'Name'];
//可选链访问数组:
let arrayItem = arr?.[42];
// new Map:
let myMap = new Map();
myMap.set("foo", {name: "baz", desc: "inga"});
let nameBar = myMap.get("bar")?.name;
// 在一个不含 bar 成员的 Map 中查找 bar 成员的 name 属性,因此结果是 undefined。
//短路计算:
let potentiallyNullObj = null;
let x = 0;
let prop = potentiallyNullObj?.[x++];
console.log(x); // x 将不会被递增,依旧输出 0
//当在表达式中使用可选链时,如果左操作数是 null 或 undefined,表达式将不会被计算
//连用可选链操作:
let cc = {
name: "张",
details: {
age: 18
}
};
let ccc = cc .details?.address?.city;
// … 可选链也可以和函数调用一起使用
let dd = ddd.trip?.getTime?.();
// 空值合并操作符可以在使用可选链时设置一个默认值:
let ee = {
name: "Carl",
details: { age: 18 }
};
let ff = ee ?.city ?? "中";
console.log(ff); // “中”