该篇文章应用的测试数据:
const a = [1, 2, 3, 4, 5];
const b = [11, 12, 13, 2, 14, 15];
- for循环、for…in、for…of
// 跳出单层循环, break, continue, 函数搭配return
for (let i = 0; i < a.length; i += 1) {
if (i === 3) {
break; //跳出循环, [1, 2, 3]
// continue; 跳出本次循环, [1, 2, 3, 5]
}
console.log(a[i]);
}
for (let i in a) {
if (i === '3') {
break;
}
console.log(a[i]); // [1,2,3]
}
// 跳出多层循环,return
testFor();
function testFor() {
console.log('444');
for (let i = 0; i < a.length; i++) {
for (let j = 0; j < b.length; j++) {
if (a[i] === b[j]) {
return false;
}
console.log('111');
}
console.log('222');
}
console.log('333');
}
// output
输入:
// 1次444
// 6次111
// 1次222
// 3次111
// for循环没有部分作用域的概念,函数有部分作用域的概念,return跳出以后作用域
// 指定label, 跳出特定循环
bbq:
for(let i = 0; i < a.length; i++){
ccc:
for(let j = 0; j < b.length; j++){
if( i === 5 ){
break bbq; //间接跳出bbq外层循环
}
}
}
- forEach、map、filter
a.forEach((item, index) => {
if (index === 3) {
return;
}
console.log(item); // [1,2,3,5]
})
// return语句跳出本次循环; break、continue语句有效; try..catch抛出异样
// 无奈终止/跳出for循环(抛出异样),应用其余形式代替
- some、every、find、findIndex
a.some((item, index) => {
if (index === 3) {
return; // 跳出本次循环
return false; // 跳出本次循环
return true; // 跳出循环
}
console.log(item);
})
a.every((item, index) => {
if (index === 3) {
return; // 跳出本次循环
return false; // 跳出循环
return true; // 跳出本次循环
}
console.log(item);
})
// some与every完结遍历的条件相同: some、find遍历中为true退出执行,every遍历中为false退出执行
发表回复