中国工信部网站备案,做词做曲网站,wordpress 图片不居中,做粥哪个美食网站好链式判断运算符 ?.
?.运算符#xff0c;直接在链式调用的时候判断#xff0c;左侧的对象是否为null或undefined。如果是的#xff0c;就不再往下运算#xff0c;而是返回undefined。
链判断运算符?.有三种写法。
obj?.prop // 对象属性是否存在 obj?.[expr] // 同上…链式判断运算符 ?.
?.运算符直接在链式调用的时候判断左侧的对象是否为null或undefined。如果是的就不再往下运算而是返回undefined。
链判断运算符?.有三种写法。
obj?.prop // 对象属性是否存在 obj?.[expr] // 同上 func?.(…args) // 函数或对象方法是否存在 下面是obj?.[expr]用法的一个例子。
let hex #C0FFEE.match(/#([A-Z])/i)?.[1];上面例子中字符串的match()方法如果没有发现匹配会返回null如果发现匹配会返回一个数组?.运算符起到了判断作用。
下面是?.运算符常见形式以及不使用该运算符时的等价形式。
a?.b
// 等同于
a null ? undefined : a.ba?.[x]
// 等同于
a null ? undefined : a[x]a?.b()
// 等同于
a null ? undefined : a.b()a?.()
// 等同于
a null ? undefined : a()Null 判断运算符 ??
读取对象属性的时候如果某个属性的值是null或undefined有时候需要为它们指定默认值。常见做法是通过||运算符指定默认值。
第一种弊端 所有的false都会取默认值
const headerText response.settings.headerText || Hello, world!;
const animationDuration response.settings.animationDuration || 300;
const showSplashScreen response.settings.showSplashScreen || true;上面的三行代码都通过||运算符指定默认值但是这样写是错的。开发者的原意是只要属性的值为null或undefined默认值就会生效但是属性的值如果为空字符串或false或0默认值也会生效。
只有为null or undefined才会取默认值
const headerText response.settings.headerText ?? Hello, world!;
const animationDuration response.settings.animationDuration ?? 300;
const showSplashScreen response.settings.showSplashScreen ?? true;上面代码中默认值只有在左侧属性值为null或undefined时才会生效。 这个运算符的一个目的就是跟链判断运算符?.配合使用为null或undefined的值设置默认值。
const animationDuration response.settings?.animationDuration ?? 300;上面代码中如果response.settings是null或undefined或者response.settings.animationDuration是null或undefined就会返回默认值300。也就是说这一行代码包括了两级属性的判断。
??本质上是逻辑运算它与其他两个逻辑运算符和||有一个优先级问题它们之间的优先级到底孰高孰低。优先级的不同往往会导致逻辑运算的结果不同。
现在的规则是如果多个逻辑运算符一起使用必须用括号表明优先级否则会报错。
(lhs middle) ?? rhs;
lhs (middle ?? rhs);(lhs ?? middle) rhs;
lhs ?? (middle rhs);(lhs || middle) ?? rhs;
lhs || (middle ?? rhs);(lhs ?? middle) || rhs;
lhs ?? (middle || rhs);逻辑赋值运算符 ||、、??
// 或赋值运算符
x || y
// 等同于
x || (x y)// 与赋值运算符
x y
// 等同于
x (x y)// Null 赋值运算符
x ?? y
// 等同于
x ?? (x y)// 老的写法
user.id user.id || 1;// 新的写法
user.id || 1;