在运算中合理使用这几种运算符,可以更简洁方便的编写代码,也更容易理解。
一、?. (可选链运算符)
允许我们读取位于连接对象链深处的属性的值,而不必显式地验证链中的每个引用是否有效
引用中是null或undefined并不会报错,表达式会短路返回值是undefined
实例:
var test = {
name: 'limei',
age: 18
},
test1 = null;
console.log(test?.name); // limei
console.log(test1?.name); // undefined
二、?? (空值合并运算符)
逻辑运算符,当左侧的表达式为null或undefined时,它会返回其右侧的表达式
与||运算符区别:||当左边为false时,就会取右侧的表达式
实例:
var test = null,
test1 = 123;
console.log(test ?? 'test为null'); // test为null
console.log(test1 ?? 456); // 123
三、! (非空断言操作符)
TypeScript中常用的操作符,表示表达式一定不是null或者undefined,可直接调用无须额外验证
实例:
var test = null,
test1 = 'abc';
console.log(test); // null
console.log(test1!.toUpperCase()); // ABC
四、注意
??与?. 运算符是JavaScript与TypeScript中都可以使用,!操作符只有在TypeScript环境中可以使用