最近在使用路由获取资源的时候,发现了这么一个逻辑运算符组合“||=”
这个是一种默认值判断赋值
比如:
this.$route.query.source ||= 0
- 如果
this.$route.query.source
的值为null
或undefined
或false
,则将0
赋给它。 - 如果
this.$route.query.source
的值已经存在且为真值(非null
、undefined
、false
),则不进行赋值操作,保持原来的值不变。
这种写法通常用于简化代码,特别是在需要给变量设置默认值时很有用。
假设 this.$route.query.source
的初值为 undefined
或者是一个假值(比如 null
或 false
),则 this.$route.query.source ||= 0
的效果就是将 0
赋给它,使得 this.$route.query.source
的值变为 0
。
如果 this.$route.query.source
的初值已经存在且为真值(比如 1
或者任何非假值),则 this.$route.query.source ||= 0
不会改变 this.$route.query.source
的值。