How to break out of forEach loop in JavaScript

錯誤範例

let numbers = [1, 2, 3, 4, 5];

numbers.forEach(number => {
  if (number === 4) {
    break; // SyntaxError: Illegal break statement
  }
  console.log(number);
});

正確用法

try + throw

var array = [1, 2, 3, 4, 5, 6, 7, 8, 9];

try {
    array.forEach(function (item, index) {
        if (item === 4) {
            throw {};
        }

        console.log(item);
    });
} catch { }

使用 filter

Filter out the values you want to skip before using forEach. This way, you avoid unnecessary iterations and can control when to stop.

let numbers = [1, 2, 3, 4, 5];

numbers
  .filter(number => number != 4)
  .forEach(number => {
    console.log(number)
  });

// The output will be:
// 1
// 2
// 3
// 5

使用 return

let numbers = [1, 2, 3, 4, 5];
let stop = false;

numbers.forEach(number => {
  if (stop) {
    return; // Skip the remaining iterations
  }
  if (number === 4) {
    stop = true; // Stop the loop after this iteration
  }
  console.log(number);
});

// The output will be:
// 1
// 2
// 3
// 4

測試, 只下 return 或 return false 是沒有效果的, 迴圈不會被跳出!


使用 every / some

  • every: 碰到return false,中止
  • some: 碰到return ture,中止
var a = [1, 2, 3, 4, 5]
a.every(function(item, index, arry) {
    console.log(item); //返回1,2
    if (item === 2) {
        return false
    } else {
        return true
    }
})
var a = [1, 2, 3, 4, 5]
a.some(function(item, index, arry) {
    console.log(item); //返回1,2
    if (item === 2) {
        return true
    } else {
        return false
    }
})

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *