forEach
forEach不能使用break和continue。return也无法退出循环。
使用break,会报错(报错信息:SyntaxError: Illegal break statement)。
使用continue,会报错(报错信息:SyntaxError: Illegal continue statement: no surrounding iteration statement)
使用return,只能跳出本次循环,并不能终止循环。
退出循环的方法:
1. 仍用 forEach:但加上try...catch...
try{ this.userList.forEach( u => { if( u.username === "admin"){ alert("找到admin用户"); throw new Error("已找到,退出循环"); } }) }catch(e){ console.log(e) };
注意:此方法将退出循环,继续执行该函数内 循环后面的代码。
若想直接退出当前函数,catch里必须有return。即try{}catch(){...return}
2. 改用 for循环
for(let i=0;i<this.userList.length;i++){ if( this.userList[i].username === "admin"){ alert("找到admin用户"); break; } }
注意:此方法将退出循环,继续执行该函数内 循环后面的代码。
若想直接退出当前函数,将break改为return。
3. 改用 some( )
this.userList.some( u =>{ if( u.username === "admin"){ alert("找到admin用户"); return true; } })
注意:some只有循环内部return true才会退出循环,继续执行该函数内 循环后面的代码。
4. 改用 every( )
this.userList.every( u =>{ if( u.username === "admin"){ alert("找到admin用户"); return false; }else{ return true; })
注意:every只要循环内部return false就会退出循环,继续执行该函数内 循环后面的代码。
标签:vue,return,admin,break,循环,报错,退出 From: https://www.cnblogs.com/lemperor/p/17271948.html