[Javascript] JS Label

Zhentiw發表於2024-11-26

For example you have nested for loop, and from inner most for loop you want to break not just inner loop but also outmost for loop how to do that?

We can use javascript label:

outer: for (let i = 0; i < 10; i++) {
  console.log('頂層迴圈');
  for (let j = 0; j < 10; j++) {
    console.log('內層迴圈', i, j);
    if (i * j > 30) {
      console.log('退出頂層迴圈');
      break outer;
    }
  }
}

It's a valid Javascript syntax which exists for many years and it's stable to use

相關文章