目录
- vue数组中不满足条件跳出循环
- 场景
- 分析
- 解决方式
- 实现
- vue数组循环遍历中途跳出整个循环
- 总结
vue数组中不满足条件跳出循环
场景
在表格中选中的数据在右边显示,在点击确定按钮时,循环判断没有填写条件名称的数据,第一个不满足条件的显示输入框,且只弹出一次警告。
分析
在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)
}
})
},
vue数组循环遍历中途跳出整个循环
vue数组循环遍历中途跳出整个循环,使用some进行循环,return true时,跳出整个循环
judgePoint(arr) {
if (this.haveError) {
this.haveError = false
}
arr.some((item, index) => {
if (item.x.match(/^(\\-|\\+)?(((\\d|[1-9]\\d|1[0-7]\\d|0{1,3})\\.\\d{0,6})|(\\d|[1-9]\\d|1[0-7]\\d|0{1,3})|180\\.0{0,6}|180)$/)) {
if (!item.y.match(/^(\\-|\\+)?([0-8]?\\d{1}\\.\\d{0,6}|90\\.0{0,6}|[0-8]?\\d{1}|90)$/)) {
this.$message({
type: \’warning\’,
message: \’点\’ + (index + 1) + \’纬度为-90~90,小数限6位\’
})
this.haveError = true
return true
}
} else {
this.$message({
type: \’warning\’,
message: \’点\’ + (index + 1) + \’经度为-180~180,小数限6位!\’
})
this.haveError = true
return true
}
});
},
总结
以上为个人经验,希望能给大家一个参考,也希望大家多多支持悠久资源网。
您可能感兴趣的文章:
- vue中v-for循环数组,在方法中splice删除数组元素踩坑记录
- vue中的循环遍历对象、数组和字符串
- vue简单的二维数组循环嵌套方式
- Vue如何循环提取对象数组中的值
- vue使用map代替Aarry数组循环遍历的方法