-
for
循环中,continue
是退出本次循环,break
是退出循环,return false
是退出循环(前提是for
循环在一个函数里面,不然会报错)
function fn(){
for (let i=0;i<5;i++){
if (i==2){
console.log(i)
// continue
break
// return false
}
console.log('i'+i)
}
}
fn()
-
forEach
循环中,break
、continue
会报错,不能用,return false
相当于for
循环中的continue
,退出本次循环(前提是forEach
循环在一个函数里面,不然会报错)
function fn1() {
['a','b','c'].forEach(item=>{
if(item==='b'){
console.log(item) // b
// continue 报错 Illegal continue statement: no surrounding iteration statement
// break 报错 Illegal break statement
return false
}
console.log(item) // a c
})
}
fn1()
-
for in
一般是循环对象的,for in
循环中,continue
是退出本次循环,break
是退出循环,return false
相当于循环中的break退出循环(前提是for in
循环在一个函数里面,不然会报错)
注:当for…in
用来遍历数组时,遍历的结果为当前元素索引值的字符串形式
function fn2() {
for(const key in ['a','b','c']){
if(key==='1'){
console.log(key) // '1'
// continue
// break
return false
}
console.log(key) // '0'
}
}
fn2()
-
for of
一般是循环内置iterator(Array, Atring, ArrayLike, Set, Map…)
或者实现了@@iterator
方法的数据类型的,for of
循环中,continue
是退出本次循环,break
是退出循环,return false
相当于循环中的break
退出循环(前提是for of
循环在一个函数里面,不然会报错)
function fn3() {
for(const item of ['a','b','c']){
if(item==='b'){
console.log(item) // b
// continue
// break
return false
}
console.log(item) // a
}
}
fn3()
网友评论