优化过多if else判断代码
有些判断难免会遇到很多 if else 看起来很头疼 下面是一个优化示例
修改前
if(this.$route.query.deptId){this.queryParams.deptId = this.$route.query.deptId}else if (this.$store.state.adaptation.roleSign.includes('fengongsicengji')) {const ancestorsId = this.$store.getters.dept.ancestors.split(',')if (ancestorsId.length === 3 || ancestorsId.length === 4) {this.queryParams.deptId = ancestorsId[2]} else if (ancestorsId.length === 2) {this.queryParams.deptId = ancestorsId[1]} else {this.queryParams.deptId = ancestorsId[2]}}
修改后
this.queryParams.deptId = this.$route.query.deptId || (this.$store.state.adaptation.roleSign.includes('fengongsicengji') ? (this.$store.getters.dept.ancestors.split(',').length === 3 ? ancestorsId[2] : ancestorsId[1]) : ancestorsId[2]);
日常中我们会忽略|| 的另一个用法
if(1||2) 这是 1或者2 通过判断
const b =?(未知值)
const a = b|| 0 当b为不为false a = b 如果为false a = 0
优雅 太优雅了 优化完整个人还是虎躯一震的 🤧🤧🤧