vue 数组中不满足条件跳出循环

49 篇文章 1 订阅
41 篇文章 0 订阅

一、场景:在表格中选中的数据在右边显示,在点击确定按钮时,循环判断没有填写条件名称的数据,第一个不满足条件的显示输入框,且只弹出一次警告。二、分析:在vue项目中,循环多数习惯会用forEach、map等方法去遍历数组,但是大家会发现在forEachforEachforEach和map中使用break和continue不仅不能调出整个循环 ,还会报错,使用return也不行。

三、解决方式:

1. 使用for循环 ;

// 普通for循环
for(let i  = 0; i <= 5; i++){
    break
}
//遍历对象:for in 返回的是索引(键值),直接拿到key
for(let key in Object){
    break
}
//遍历数组: for of 返回元素,不可用于原对象(没有索引)
for(let item of Array){
    break
}

2. 使用try-catch-finally处理forEach的循环;

try{ 
 // 可能会导致错误的代码
} catch(error){ 
 // 在错误发生时怎么处理
} finally {
 // 只要代码中包含 finally 子句,那么无论try 还是catch 语句块中的return 语句都将被忽略。
}

let arr= [1, 2, 'lemon', 4, 5,'666']
try {
   arr.forEach(item => {
        // 元素达到条件时需要抛出的异常,再catch中处理
        if (item === 'lemon') {
            throw new Error("lemon")
        } else {
            throw new Error("other")
        }
  })
} catch (e) {
    // 异常抛出时你想要做的操作
    console.log(e.massage);
} finally {
    console.log(1) //一定会执行的操作
}

 3. 使用some方法return true跳出循环,数组里面所有的元素有一个符合条件就返回true;

let arr = [1, 2, 'lemon', 4, 5,'666']
arr.some((item) => {
    if (item === 'lemon') {
        return true
    }
})

4. every()使用return false 跳出循环,数组里面所有的元素都符合条件就返回true;

let arr = [1, 2, 'lemon', 4, 5,'666']
arr.every((item) => {
    if (item === 'lemon') {
        return false
    } else {
        return true
    }
})

 四、实现:综上所述,最终使用some方法对于上面需求实现是最简单便捷的。

    //提交  this.selectedArr:选中的数据
    async submit() {
      if (this.selectedArr.length > 0) {
        this.btn_loading = true
        this.selectedArr.some((item) => {
            if (!item.name) {
                // 显示输入框
              this.selctEditClick(item)
              this.$message.warning('条件名称不能为空')
              this.btn_loading = false
              return true
            }
        }) 
      } else {
          this.$message.warning('请选择要添加的条件数据')
      }
    },

     // 选中数据字段编辑
    selctEditClick(data) {
      this.selectedArr.forEach((item) => {
        this.$set(item, 'isEdit', false)
        if (item.keyId == data.keyId) {
          this.$set(item, 'isEdit', true)
        }
      })
    },
  • 2
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值