在很多场景中 我们需要判断是否满足条件 满足条件拿到数据或者提示信息中止循环 且中止下面代码的继续执行 多用在登录判断 用户信息填写 绑定手机号密码等的判空和正则判断
1 首先最简单的 if判断符合条件 中止程序执行 用return 中止代码继续执行
if (this.form.nation == '') {
this.isshow = true;
this.isShowMsg = '请选择民族';
setTimeout(() => {
this.isshow = false;
}, 3000)
return;//中止程序执行 不要继续提交数据 造成接口报错
}
2 for循环判断符合条件 中止代码执行 break /continue
var arr = [1,3,5,7,9];
var id = 5;
for (var i = 0; i < arr.length; i++) {
if(arr[i]=== 1) {
continue;//跳过当次循环
return
}
if (arr[i] === id) {
break;//满足条件,跳出循环
return
}
}
3 forEach 判断符合条件 中止循环并中止程序 try{throw new Error()}.catch(){} 抛出异常强行中止循环
首先 forEach是没有 break和continue的 写了会报错
return false/return只会中止本次循环而不会让全部的循环不再执行
forEach可以通过抛出异常的方式强行中止循环
try {
this.sxkm.forEach(ele => {
if (this.sxkmarr[ele.value - 1] == '') {
//有空值
this.isshow = true;
this.isShowMsg = '请填写完整选考科目成绩';
setTimeout(() => {
this.isshow = false;
}, 3000)
throw new Error("breakForEach");
} else if (!(/^[0-9]+$/.test(this.sxkmarr[ele.value - 1]))) {
this.isshow = true;
this.isShowMsg = '请填写正确的选考科目成绩';
setTimeout(() => {
this.isshow = false;
}, 3000)
throw new Error("breakForEach");//抛出异常 中止循环
}
})
} catch (e) {
if (e.message != "breakForEach") throw e;
return; //结束代码 后面代码不再执行
}