for循环
- 使用break,可以中断循环
let arr = [1,2,3,4,5,6,7,8,9]
for(let i = 0; i< arr.length; i++){
if(i === 5){
break;
}
console.log(arr[i])
}
- 使用continue,循环可以继续
let arr = [1,2,3,4,5,6,7,8,9]
for(let i = 0; i< arr.length; i++){
if(i === 5){
continue;
}
console.log(arr[i])
}
- 使用return,会报错
let arr = [1,2,3,4,5,6,7,8,9]
for(let i = 0; i< arr.length; i++){
if(i === 5){
return;
}
console.log(arr[i])
}
for...in 循环
- 使用break,可以跳出循环
let arr = [1,2,3,4,5,6,7,8,9]
for(let i in arr){
if(i == 5){
break;
}
console.log(arr[i])
}
- 使用continue
let arr = [1,2,3,4,5,6,7,8,9]
for(let i in arr){
if(i == 5){
continue;
}
console.log(arr[i])
}
for...in使用continue继续循环.PNG
- 使用return,报错
let arr = [1,2,3,4,5,6,7,8,9]
for(let i in arr){
if(i == 5){
return;
}
console.log(arr[i])
}
for...of循环
- 使用break,
let arr = [1,2,3,4,5,6,7,8,9]
for(let item of arr){
if(item == 5){
break;
}
console.log(item)
}
- 使用continue,会跳出当前循环继续循环
let arr = [1,2,3,4,5,6,7,8,9]
for(let item of arr){
if(item === 5){
continue;
}
console.log(item)
}
- return ,报错
let arr = [1,2,3,4,5,6,7,8,9]
for(let item of arr){
if(item == 5){
return;
}
console.log(item)
}
forEach
- 使用break,报错
let arr = [1,2,3,4,5,6,7,8,9]
arr.forEach((item) => {
if(5 === item){
break;
}
console.log(item)
})
- 使用continue,报错
let arr = [1,2,3,4,5,6,7,8,9]
arr.forEach((item) => {
if(5 === item){
continue;
}
console.log(item)
})
- 使用return会跳出当前循环,但不会终止循环
let arr = [1,2,3,4,5,6,7,8,9]
arr.forEach((item) => {
if(5 === item){
return;
}
console.log(item)
})
filter
- 使用break,报错
let arr = [1,2,3,4,5,6,7,8,9]
let result = []
result = arr.filter((item) => {
if(5 === item){
break;
}
return item
})
console.log(result)
- 使用continue,报错
let arr = [1,2,3,4,5,6,7,8,9]
let result = []
result = arr.filter((item) => {
if(5 === item){
continue;
}
return item
})
console.log(result)
- 使用break,会跳出当前循环,继续
let arr = [1,2,3,4,5,6,7,8,9]
let result = []
result = arr.filter((item) => {
if(5 === item){
return;
}
return item
})
console.log(result)
map
- 使用break,报错
let arr = [1,2,3,4,5,6,7,8,9]
let result = []
result = arr.map((item) => {
if(5 === item){
break;
}
return item
})
console.log(result)
- 使用continue,报错
let arr = [1,2,3,4,5,6,7,8,9]
let result = []
result = arr.map((item) => {
if(5 === item){
continue;
}
return item
})
console.log(result)
- 使用return,不会报错
let arr = [1,2,3,4,5,6,7,8,9]
let result = []
result = arr.map((item) => {
if(5 === item){
return;
}
return item
})
console.log(result)