代码
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<script type="text/javascript" src="js/jquery.min.js"></script>
<script type="text/javascript">
// 所有学生
var allStudent=[
{no:'s001',name:'学生1',address:'地址1'},
{no:'s002',name:'学生2',address:'地址2'},
{no:'s003',name:'学生3',address:'地址3'},
{no:'s004',name:'学生4',address:'地址4'},
{no:'s005',name:'学生5',address:'地址5'},
{no:'s006',name:'学生6',address:'地址6'},
{no:'s007',name:'学生7',address:'地址7'},
{no:'s008',name:'学生8',address:'地址8'},
];
//jquery 循环,并跳出循环
function jqueryEach(){
$.each(allStudent,function(i,item){
console.log(item.name);
if(item.no==='s003'){
return false;
}
});
console.log("结束了") ;
}
//es6 循环,并跳出循环
function es6ForEach(){
try{
allStudent.forEach((item,i)=>{
console.log(item.name);
if(item.no==='s004'){
//报错,就跳出循环
throw new Error("ending");
}
});
}catch(e){
if(e.message == "ending"){
console.log("结束了") ;
}else{
console.log(e.message);
}
}
}
$(function(){
jqueryEach();
es6ForEach();
});
</script>
</head>
</html>
结果