今天使用vue開發(fā)一個(gè)小功能,用到了v-if,代碼如下:
<el-tab-pane v-if="tabIsShow('roomData')" label="直播間基礎(chǔ)信息" name="roomData">
</el-tab-pane>
tabIsShow (tabName) {
let flag = false;
if(!this.vipContent || this.vipContent.length === 0) {
return flag;
}
for(let i=0; i< this.vipContent.length ; i++){
if(this.vipContent[i] === tabName) {
flag = true;
break;
}
}
return flag;
},
這是修改之后的代碼,之前tabIsShow中的for循環(huán),我使用的是forEach,代碼如下:
tabIsShow (tabName) {
if(!this.vipContent || this.vipContent.length === 0) {
return false;
}
this.vipContent.forEach(item=> {
if(item === tabName) {
return true;
}
})
return true;
},
打斷點(diǎn),調(diào)試了若干次,顯示結(jié)果就是不對(duì),程序明明已經(jīng)執(zhí)行到 return true了,但是顯示結(jié)果就是不對(duì),后來,百度之后才明白,原來使用return無法終止forEach。
一、終止forEach嘗試
1.使用return,只能終止當(dāng)次循環(huán),效果類似于for循環(huán)的continue
運(yùn)行如下代碼:
let arr = [1,2,3,4,5];
arr.forEach(item=>{
if(item === 3) {
console.log("進(jìn)入if,滿足條件"); // 第一個(gè)console
return;
console.log("1.我怎么還能執(zhí)行呢?"); // 第二個(gè)console
}
console.log("item=" + item); // 第三個(gè)console
});
運(yùn)行結(jié)果為:

運(yùn)行結(jié)果
從中,我們可以看出,使用return只能跳出當(dāng)次循環(huán),類似于for循環(huán)中的continue,程序并不會(huì)終止。
2.在forEach中使用break或者continue是違法的

嘗試使用break與continue報(bào)錯(cuò)
二、終止forEach終止正確方法
其實(shí),我認(rèn)為如何終止forEach循環(huán)其實(shí)并不重要,因?yàn)槿绻阈枰谘h(huán)中終止循環(huán),完全可以試用for循環(huán)來代替。真正重要的是你要知道,直接return,你是無法直接退出forEach的。
但是做事情要有始有終,在這里,我就簡(jiǎn)單的說一下如何終止forEach。
1.用過拋出異常的方式終止forEach
try{
var arr = [1,2,3,4,5];
arr.forEach(item=>{
if(item === 3) {
throw new Error("EndIterative");
}
console.log("item=" + item);
});
} catch(e) {
if(e.message != "EndIterative") {
throw e;
}
}
運(yùn)行結(jié)果如下:

異常拋出終止forEach