var arr = ['a','b','c','d']
for循环
for (var i=0; i<arr.length; i++) {
if (i==1) {
console.log(arr[i])
break
}
}
/*
break跳出循环
输出结果:'a','b'
*/
for (var i=0; i<arr.length; i++) {
if (i==1) {
continue
}
console.log(arr[i])
}
/*
continue跳出本次循环
输出结果:'a','c','d'
*/
forEach
arr.forEach(function(item,index){
if (index==1) {
return
}
console.log(item)
})
/*
return仅会跳出本次循环
输出结果:'a','c','d'
*/
try{
arr.forEach(function(item,index){
if(index == 1){
throw 'out';
}
console.log(item);
});
}catch(e){}
/*
只有通过try-catch的方式才能够使forEach跳出整个循环
输出结果:'a'
*/
map
// map是为了返回值,如果跳出循环的话,返回值就不对
arr.map(function(item,index){
if (index==1) {
return
}
console.log(item)
})
/*
return仅会跳出本次循环
输出结果:'a','c','d'
返回值:[undefined,undefined,undefined,undefined]
*/
try{
arr.map(function(item,index){
if(index == 1){
throw 'out';
}
console.log(item);
});
}catch(e){}
/*
只有通过try-catch的方式才能够使forEach跳出整个循环
输出结果:'a'
返回值:undefined
*/
$.each
$.each(arr,function(index,item){
if (index==1) {
return true
}
console.log(item)
})
/*
return true跳出当前循环
输出结果:'a','c','d'
*/
$.each(arr,function(index,item){
if (index==1) {
return false
}
console.log(item)
})
/*
return false跳出整个循环
输出结果:'a'
*/
相关文章链接:js forEach、each、map、 for...in、for...of、filter、find
网友评论