一、?.用法
let a = {
name:2
}
let b = a?.name
console.log(b)
/**只有a有name这个属性时,才会把name的值赋值给b
* 如果a没有name这个属性,则b为undefined
*/
二、??
let a = undefined //或者null
let c = 1
let b = a??c
console.log(b)
/*
如果a为undefined或者null,则把c的值赋给b
否则把a的值赋给b
*/
output:1
三、??=
let a = 12 //或者null
let c = 1
let b = a??=c
console.log(b)
/*
let b = a??=c:当a的是undefined或者null时,把c的值赋值给a,即相当于let b = c
当a的值非undefined或者null时,即相当于let b = a
*/
本文详细介绍了JavaScript中的三目运算符的两种用法:?. 和 ??=. 首先,?.运算符用于在访问对象属性时,如果中间路径为undefined或null,将停止访问并返回undefined,否则返回属性值。其次,??=运算符在变量为undefined或null时,会赋予其右侧表达式的值,否则保持变量原有值。这些运算符在JavaScript编程中提供了更简洁的语法糖,提高了代码的可读性和效率。

被折叠的 条评论
为什么被折叠?



