새소식

DevLog/Error

[JavaScript] Uncaught SyntaxError: Illegal break statement

  • -

오류 발생 코드

collisionCheck() {
    chunkedMap1.tiles.forEach((arr) => {
      if (
        this.position.x < arr.x + tileSize &&
        this.position.x + tileSize > arr.x &&
        this.position.y + tileSize > arr.y &&
        this.position.y < arr.y + tileSize
      ) {
        if (this.vx < -velocity) {
          this.position.x = arr.x + tileSize + 0.01;
          break
        }
        if (this.vx > velocity) this.position.x = arr.x - tileSize - 0.01;
        if (this.vy < -velocity) this.position.y = arr.y + tileSize + 0.01;
        if (this.vy > velocity) this.position.y = arr.y - tileSize - 0.01;
      }
    });
  }
}

 

There is no way to stop or break a forEach() loop other than by throwing an exception. If you need such behavior, the forEach() method is the wrong tool.

 

break문은 반복문을 빠져나올 때 사용한다. for, while, do-while문에는 사용이 가능하지만

forEach문에는 break, continue를 사용할 수 없음.

사용하려면 for문을 사용할 것!

 

 

 

 

참고 자료

 

Array.prototype.forEach() - JavaScript | MDN

The forEach() method of Array instances executes a provided function once for each array element.

developer.mozilla.org

 

Contents

포스팅 주소를 복사했습니다

이 글이 도움이 되었다면 공감 부탁드립니다.