0

js 跳出循环/结束遍历的方法

 2 years ago
source link: https://segmentfault.com/a/1190000040824320
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

js 跳出循环/结束遍历的方法

发布于 35 分钟前

该篇文章使用的测试数据:

const a = [1, 2, 3, 4, 5];
const b = [11, 12, 13, 2, 14, 15];
  1. 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外层循环
        }
    }
}
  1. forEach、map、filter
a.forEach((item, index) => {
    if (index === 3) {
        return;
    }
    console.log(item); // [1,2,3,5]
})

// return语句跳出本次循环; break、continue语句无效; try..catch抛出异常
// 无法终止/跳出for循环(抛出异常),使用其他方式替代
  1. 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退出执行

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK