欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

JavaScript跳出循環(huán)的常用方法詳解

 更新時(shí)間:2025年03月20日 10:23:07   作者:simahe  
這篇文章主要介紹了JavaScript中常用的遍歷數(shù)組的方式以及如何提前退出循環(huán),常用退出循環(huán)的方式包括break、continue、return和throw,文中通過代碼介紹的非常詳細(xì),需要的朋友可以參考下

前言

JavaScript 中常用的遍歷數(shù)組的方式有:for、for-offorEach、map 等,當(dāng)我們循環(huán)數(shù)組時(shí)有些情況下會提前退出循環(huán),終止迭代,比如: 已找到目標(biāo)元素,或者滿足某個(gè)條件,這樣能避免不必要的計(jì)算,優(yōu)化程序性能 。

1、常用退出循環(huán)方式

JavaScript 中提供了兩種退出循環(huán)的方法: breakcontinue

  • break: 立即終止所有循環(huán),執(zhí)行循環(huán)之后的代碼。
  • continue :立即終止當(dāng)前循環(huán),開始下一次循環(huán)。

1-1 使用 break 跳出循環(huán)

示例:

for (let i = 0; i < 10; i++) {
  if (i === 5) {
    break; // 當(dāng) i 等于 5 時(shí)跳出循環(huán)
  }
  console.log(i); // 輸出 0, 1, 2, 3, 4
}
console.log('break跳出for循環(huán)');

1-2 使用 continue 跳出循環(huán)

示例:

for (let i = 0; i < 10; i++) {
  if (i === 5) {
    continue; // 當(dāng) i 等于 5 時(shí)跳過當(dāng)前循環(huán),進(jìn)行下一次循環(huán)
  }
  console.log(i); // 輸出 0, 1, 2, 3, 4, 6, 7, 8, 9,沒5
}

2、forEach、Map 能否跳出循環(huán)

上面我們已經(jīng)介紹了 for 是可以跳出循環(huán)的,那么 forEach、Map 能否跳出循環(huán)?

首先我們使用break、continue;

示例:

const _array = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
_array.forEach((item) => {
  if (item === 5) {
    //break;//Jump target cannot cross function boundary
    //continue;//Jump target cannot cross function boundaryS
  }
  console.log(item);
});

可以看到 break、continue 不能再函數(shù)里面使用, forEach 、map 在循環(huán)時(shí)給每個(gè)元素套了一個(gè)函數(shù)。

我們在試試 return方法。

示例:

//方法一
const _array = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
_array.forEach((item) => {
  if (item === 5) {
    return; // 當(dāng) i 等于 5 時(shí)跳過
  }
  console.log(item); // 0,1,2,3,4,6,7,8,9
});
//方法二,在函數(shù)里面使用return
function testReturn() {
  const _array = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
  _array.forEach((item) => {
    if (item === 5) {
      return; // 當(dāng) i 等于 5 時(shí)跳過
    }
    console.log(item); // 0,1,2,3,4,6,7,8,9
  });
}
testReturn();

return 語句用于終止函數(shù)執(zhí)行,也只能跳出當(dāng)前函數(shù)。我們在查查 MDN,發(fā)現(xiàn)一個(gè)throw.

3 強(qiáng)大的 throw

throw 語句用于拋出用戶自定義的異常。當(dāng)前函數(shù)的執(zhí)行將停止(throw 之后的語句不會被執(zhí)行),并且控制權(quán)將傳遞給調(diào)用堆棧中第一個(gè)catch塊。

示例:

let result = 0;
try {
  console.log(
    '首先執(zhí)行 try 塊中的代碼,如果它拋出異常,則將執(zhí)行 catch 塊中的代碼。'
  );
  const _array = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
  _array.forEach((item) => {
    if (item === 5) {
      throw item; //**拋出錯(cuò)誤**
    }
    console.log(item); //0,1,2,3,4
  });
} catch (e) {
  console.log('catch里面給e:' + e); //catch里面給e:5
  result = e;
} finally {
  console.log('finally 塊中的代碼退出之前始終被執(zhí)行:' + result); //finally 塊中的代碼退出之前始終被執(zhí)行:5
}
console.log(result); //等到我們想要的值5

我們發(fā)現(xiàn) throw 可以跳出循環(huán)。

現(xiàn)在我們來做一個(gè)簡單的總結(jié):

1、可以使用 break 直接跳出循環(huán);

2、可以使用 continue 跳過當(dāng)前循環(huán),進(jìn)入下一次循環(huán);

3、可以使用 return退出當(dāng)前函數(shù)執(zhí)行;

4、可以使用try-catch-throw強(qiáng)制退出循環(huán)。

4、怎么退出嵌套循環(huán)

工作中經(jīng)常碰到一些嵌套數(shù)據(jù),當(dāng)我們找到想要的數(shù)據(jù),為了節(jié)約時(shí)間,考慮怎么退出循環(huán)。

4-1 使用 break 跳出嵌套循環(huán)

示例:

for (let i = 0; i <= 5; i++) {
  for (let j = 0; j <= 5; j++) {
    if (j === 3) {
      break;
      //continue;
    }

    console.log(`i: ${i}, j: ${j}`);
  }
  //`break` 語句用于立即終止最內(nèi)層的循環(huán),并繼續(xù)執(zhí)行下一條語句。
  console.log('跳出break,指向這里');
}

//i: 0, j: 0
// i: 0, j: 1
// i: 0, j: 2
// 跳出break,指向這里
// i: 1, j: 0
// i: 1, j: 1
// i: 1, j: 2
// 跳出break,指向這里

break 只能跳出最里面的循環(huán),跳不出多層循環(huán)

4-2 使用 return 跳出嵌套循環(huán)

示例:

function testReturn() {
  for (let i = 0; i <= 5; i++) {
    for (let j = 0; j <= 5; j++) {
      if (j === 3) {
        return { i, j };
      }
      console.log(`i: ${i}, j: ${j}`);
    }
  }
}
console.log(testReturn());
//i: 0, j: 0
// i: 0, j: 1
// i: 0, j: 2
// {i: 0,j: 3}

return 語句用于終止函數(shù)執(zhí)行,可以跳出多層循環(huán)

4-3 使用 try-catch-throw跳出嵌套循環(huán)

示例:

let result = 0;
try {
  for (let i = 0; i < 5; i++) {
    for (let j = 0; j < 5; j++) {
      if (j === 3) {
        throw j;
      }
      console.log(`i: ${i}, j: ${j}`);
    }
  }
} catch (e) {
  console.log('catch里面給e:' + e); //catch里面給e:3
  result = e;
}
console.log(result); //3

//i: 0, j: 0
//i: 0, j: 1
//i: 0, j: 2
//catch里面給e:3
//3

try-catch-throw也可以跳出多層循環(huán)

4-4 使用 標(biāo)簽語句outerLoop

示例:

outerLoop: for (let i = 0; i <= 5; i++) {
  for (let j = 0; j <= 5; j++) {
    if (j === 3) {
      break outerLoop; // 跳出外層循環(huán)
    }
    console.log(`i: ${i}, j: ${j}`);
  }
}

//i: 0, j: 0
//i: 0, j: 1
//i: 0, j: 2

在這個(gè)例子中,outerLoop是一個(gè)標(biāo)簽,它標(biāo)記了外層的for循環(huán)。當(dāng)內(nèi)層的if條件滿足時(shí),break outerLoop;語句會跳出到outerLoop標(biāo)簽處,從而終止兩層循環(huán)的執(zhí)行。

現(xiàn)在我們來做一個(gè)簡單的總結(jié):

1、可以將嵌套循環(huán)丟在函數(shù)中,使用 return 直接跳出函數(shù),跳出循環(huán);
2、可以使用 break配合 outerLoop 跳出循環(huán);
3、可以使用try-catch-throw強(qiáng)制退出循環(huán)。

5、數(shù)組中那些可以提前結(jié)束迭代的方法

  • every:都滿足。那么只要返回 false 就回提前結(jié)束。
  • some:至少有一個(gè)元素滿足。那么只要返回 true 就回提前結(jié)束。
  • find、findIndex、includes 等:滿足條件提前結(jié)束;
const _array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
console.log('every');
_array.every((item) => {
  if (item == 2) {
    return false; //不滿足條件返回false
  }
  console.log(item); //1
});

console.log('some');
_array.some((item) => {
  if (item == 2) {
    return true; //一個(gè)滿足返回true
  }
  console.log(item); //1
});

console.log('find');
const found = _array.find((item) => item === 2);
console.log(found); //2

console.log('findIndex');
const findIndex = _array.findIndex((item) => item === 2);
console.log(findIndex); //1

6、最后總結(jié)

  • 優(yōu)先使用數(shù)組已有的方式:includes、every、some等;
  • 在考慮使用 breakcontinue跳出循環(huán);
  • return跳出函數(shù)也是一種選擇;
  • 至于異常try-catch-throw可以在特殊情況下退出多層循環(huán),不建議頻繁使用。
  • 最后outerLoop結(jié)合break慎用;

總結(jié) 

到此這篇關(guān)于JavaScript跳出循環(huán)的常用方法的文章就介紹到這了,更多相關(guān)JS跳出循環(huán)方法內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

最新評論