JS_객체와 배열의 순회 Iteration

金秀·2021년 9월 6일
0

JS 개념정리

목록 보기
14/15
post-thumbnail

객체에서 key 값 가져오기

1.for/in
The for...in statement iterates over all enumerable properties of an object that are keyed by strings (ignoring ones keyed by Symbols), including inherited enumerable properties.
for/in 은 객체 순회 조심 & 자연스러지 않음
for/in은 순회하려고 만들어진 자료구조가 아닌..
obj 안의 프로토타입까지 다 순회하고
상속받은 모든 키를 다(enumerable properties) 가져옴!

2.hasOwnProperty

포로토타입체인을 가져오고 싶지 않을 때
딱 key만 가져오고 싶을 때
hasOwnProperty 사용함

3.Object.keys💙
https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Global_Objects/Object/defineProperties

enumerable vs iterable

enumberable
개체를 나열할 때 속성(나열 가능한지 아닌지)
true일 경우 해당 객체의 속성을 열거할 때 열거됨 default false

iterable
iteration protocol 규약(큰 약속)
배열은 iterable 하다.
obj는 iterable 하지 않음

iteration protocol을 따르는 애들은 iterable함
(배열,유사배열,제너레이터 등)

배열 & array-like

Array() 와 Node()로 태생이 다르지만
똑같이 iterable protocol을 따르고 있음

iteration protocol

iteration protocol을 따르면 for/of, spread 연산자 가능함
for/of 로는 노드/어레이 등을 of 뒤에 넣고 순회가능함.

✔ 레퍼런스 자료

MDN iterable protocol
https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Iteration_protocols

profile
기록하기

0개의 댓글

관련 채용 정보