Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

JavaScript의 for each, for in, for of 비교 #1

Open
dididy opened this issue Jan 24, 2021 · 0 comments
Open

JavaScript의 for each, for in, for of 비교 #1

dididy opened this issue Jan 24, 2021 · 0 comments

Comments

@dididy
Copy link
Member

dididy commented Jan 24, 2021

for each

for each 구문은 array에서만 사용할 수 있다. 인자로 callback 함수를 등록하여 배열 요소와 index에 접근해 사용할 수 있다. 성능은 좋지만 break을 지원하지 않는다. callback 함수의 return이 true든 false든 둘 다 continue 처리되어 루프를 전부 돌게 된다. for each 자체의 return은 undefined이다.

break을 사용하기 위해 try, catch를 사용할 수 있지만, 코드가 지저분해질 수 있다. 더 우아한 방법으로 for each 대신에 every나 some을 사용하면 된다.

두 메서드 모두 for each처럼 배열을 순회할 때 사용된다. 조건에 만족하는 값이 있는 경우(즉, callback 함수에 return 값이 존재하는 경우) 루프를 중지하고 every의 경우 메서드 자체에서 false를 return하고 some의 경우 메서드 자체에서 true를 return 한다.

for in

객체에서 순회가 필요할 때 사용된다. [[Enumerable]] 이 true인 것만 순회하게 되어있어 객체의 내장 메서드나 내장 프로퍼티 등 비열거형인 경우에는 순회하지 않는다.

for of

for each에 비해 느리다.(사실 플랫폼마다 다르다고 함) 사용하기 위해서는 컬렉션 객체가 [Symbol.iterator] 속성을 가지고 있어야 한다.

index를 사용하고 싶으면 아래와 같이 entires 메소드를 사용하면 된다.

for (const [index, each] of ['a', 'b', 'c'].entries()) {
  console.log(index, each);
}

References

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

1 participant