for...in & for...of 정리
for…in은 ‘객체’를 순환하고, for…of는 ‘배열’을 순환한다.
1. for…in은 객체를 순환한다.
객체의 키 값이 순환된다.
const object = {
a: 1,
b: 2,
c: 3
};
for (const key in object) {
if (Object.hasOwnProperty.call(object, key)) {
console.log(key); // a b c
}
}
for…of로는 객체를 순환할 수 없다.
객체가 항상 iterable은 아니기 때문이다.
2. for…of는 배열을 순환한다.
배열의 ‘값’이 순환된다.
const array = [1, 2, 3];
for (const iterator of array) {
console.log(iterator); // 1 2 3
}
for …in으로도 배열을 순환할 수 있다.
자바스크립트에서 배열은 곧 객체이기 때문이다.
for (const key in array) {
if (Object.hasOwnProperty.call(array, key)) {
console.log(key); // 0 1 2
}
}
다만, 배열의 ‘값’이 아니라 ‘인덱스’가 순환된다.
참고문헌
https://velog.io/@eomttt