文章詳情頁
vue數組中不滿足條件跳出循環問題
瀏覽:28日期:2022-06-12 18:22:32
目錄vue數組中不滿足條件跳出循環場景分析解決方式實現vue數組循環遍歷中途跳出整個循環總結vue數組中不滿足條件跳出循環場景
在表格中選中的數據在右邊顯示,在點擊確定按鈕時,循環判斷沒有填寫條件名稱的數據,第一個不滿足條件的顯示輸入框,且只彈出一次警告。
在vue項目中,循環多數習慣會用forEach、map等方法去遍歷數組,但是大家會發現在forEachforEachforEach和map中使用break和continue不僅不能調出整個循環 ,還會報錯,使用return也不行。
1. 使用for循環 ;
// 普通for循環for(let i = 0; i <= 5; i++){ break}//遍歷對象:for in 返回的是索引(鍵值),直接拿到keyfor(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 = truethis.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} }); },總結以上為個人經驗,希望能給大家一個參考,也希望大家多多支持好吧啦網。
標簽:
JavaScript
相關文章:
排行榜
