溫馨提示×

es6怎么終止foreach循環

es6
小億
264
2023-12-21 17:22:00
欄目: 編程語言

在ES6中,foreach循環是無法直接終止的,因為它沒有內置的終止機制。然而,你可以使用for...of循環或some方法來實現類似的功能。

使用for...of循環時,你可以使用break關鍵字來終止循環,例如:

const array = [1, 2, 3, 4, 5];

for (const item of array) {
  if (item === 3) {
    break; // 終止循環
  }
  console.log(item);
}

使用some方法時,當回調函數返回true時,循環將會被終止,例如:

const array = [1, 2, 3, 4, 5];

array.some((item) => {
  if (item === 3) {
    return true; // 終止循環
  }
  console.log(item);
});

需要注意的是,for...of循環和some方法都只能終止當前循環,而無法直接終止外層循環。如果你需要終止外層循環,你可以使用label語句來實現,例如:

outerLoop: for (const item1 of array1) {
  for (const item2 of array2) {
    if (item2 === 3) {
      break outerLoop; // 終止外層循環
    }
    console.log(item1, item2);
  }
}

0
亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女