자료 출처 - 모던 JavaScript 튜토리얼

한꺼번에 나가고 싶어 🤔

for-loop를 쓰다보면 이중 루프를 한꺼번에 나가고 싶은 생각이 들곤 한다. 나는 C++을 쓸 때 이러한 문제를 boolean 타입의 변수를 써서 해결하곤 한다.

for (int i = 0; i < length; ++i) {
  bool isFit = false;
  for (int j = 0; j < length; ++j) {
    if (condition) {
      isFit = true;
      break;
    }
  }
  if (isFit) break;
}

JS에는 label이 있다 ⁉️

outer: for (let i = 0; i < len; ++i) {
  for (int j = 0; j < len; ++j) {
    if (condition) break outer;
  }
}

for-loop 앞에 레이블 이름을 지정해주고 break labelName;을 해주면 외부 반복문까지 빠져나갈 수 있다.

0개의 댓글

Powered by GraphCDN, the GraphQL CDN