指数运算符
2 ** 2 // 4
2 ** 3 // 8
这个运算符的一个特点是右结合,而不是常见的左结合。多个指数运算符连用时,是从最右边开始计算的
// 相当于 2 ** (3 ** 2)
2 ** 3 ** 2
// 512
上面代码中,首先计算的是第二个指数运算符,而不是第一个
指数运算符可以与等号结合,形成一个新的赋值运算符(`**=`)
let a = 1.5;
a **= 2;
// 等同于 a = a * a,就是 a = a 的平方
let b = 4;
b **= 3;
// 等同于 b = b * b * b,就是 b = b 的三次方
链判断运算符
// es5 的写法
const firstName = (message
&& message.body
&& message.body.user
&& message.body.user.firstName) || 'default';
// es6 的写法
const firstName = message?.body?.user?.firstName || 'default';
上面代码使用了?.运算符,直接在链式调用的时候判断,左侧的对象是否为 null 或 undefined。如果是的,就不再往下运算,而是返回 undefined
链判断运算符 ?.
有三种写法
obj?.prop // 对象属性是否存在
obj?.[expr] // 同上
func?.(...args) // 函数或对象方法是否存在
下面是 ?.
运算符常见形式,以及不使用该运算符时的等价形式
a?.b
// 等同于
a == null ? undefined : a.b
a?.[x]
// 等同于
a == null ? undefined : a[x]
a?.b()
// 等同于
a == null ? undefined : a.b()
a?.()
// 等同于
a == null ? undefined : a()
Null 判断运算符
读取对象属性的时候,如果某个属性的值是 null
或 undefined
,有时候需要为它们指定默认值。常见做法是通过 ||
运算符指定默认值
const headerText = response.settings.headerText || 'Hello, world!';
const animationDuration = response.settings.animationDuration || 300;
const showSplashScreen = response.settings.showSplashScreen || true;
上面的三行代码都通过 `||` 运算符指定默认值,但是这样写是错的。
开发者的原意是,只要属性的值为 null 或 undefined,默认值就会生效,但是属性的值如果为空字符串或 false 或 0,默认值也会生效
为了避免这种情况,ES2020 引入了一个新的 Null 判断运算符 ??
。它的行为类似 ||
,但是只有运算符左侧的值为 null
或 undefined
时,才会返回右侧的值
const headerText = response.settings.headerText ?? 'Hello, world!';
const animationDuration = response.settings.animationDuration ?? 300;
const showSplashScreen = response.settings.showSplashScreen ?? true;
上面代码中,默认值只有在左侧属性值为 nul l或 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);
(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)
这三个运算符 ||=
、&&=
、??=
相当于先进行逻辑运算,然后根据运算结果,再视情况进行赋值运算
网友评论