我原来的代码是四五层if else,像金字塔一样,真的糟心,
最近做项目时遇到多个条件判断,方法里面if else嵌套太多,优化一下
一直用ES6的forEach和map,才知forEach中不支持终止循环,然后for-in好像问题挺多,最后用for-of解决了问题
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
showAgent () { // 这里if + reurn 抛出错误 if (this.idsString.length === 0) { return this.$message.error(this.$t('common.pls_select')) } if (this.idsString.length > 5) { return this.$message.error(this.$t('product.max_select_agent')) } for (let item of this.multipleSelection) { if (item.is_del !== 0) { this.$message.error(this.$t('product.product_status_tips')) // 直接退出函数,不执行下面的任何方法,以及for外面的代码 return false } if (item.is_agent === 1) { this.$message.error('已经是供销产品') return false } } // 没有任何错误时才执行下面的代码 this.agentDialogVisable = true this.agentForm.agentTableData = this.multipleSelection } |
还有beeak, continue,遇到if后会继续执行
关于for of 和 for in的区别可以参考:https://www.mkboke.com/note-book/javascript/228/