?? 空值合并操作符
只有当左侧为null和undefined时,才会返回右侧的数
const foo = null ?? 'default string';
console.log(foo); // "default string"
const baz = 0 ?? 42;
console.log(baz); // 0
?. 可选链操作符
const adventurer = {
name: 'Alice',
cat: {
name: 'Dinah'
}
};
const dogName = adventurer.dog?.name;
console.log(dogName); // undefined
使用语法:obj?.prop obj?.[expr] arr?.[index] func?.(args)
!. 非空断言操作符(ts中使用)
!:非空类型断言 表示确定某个标识符是有值的,跳过ts在编译阶段对它的检测
function aa(value?:string){
console.log(value!.length);
// console.log(value.length); //错误提醒: value is possibly 'undefined'.
}
aa('ppp');
//实际上这个东东不好用, 因为不传值, 编译JS后, 会报错, 所以建议使用?. 替代 !.
附
- || 操作符:左侧为null, 0, undefined时执行右边
- && 操作符:左侧为隐性转化为true时执行右边