key
값에 접근할 수 있지만, value
값에 접근하는 방법은 제공하지 않습니다.const obj = {
name: 'John',
age: '30',
}
for(const key in obj) {
console.log(`${key} ${obj[key]}`);
// name john, age 30
}
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...in
const arr = ['사과', '바나나', '멜론'];
for(const fruit of arr) {
console.log(fruit);
// 사과, 바나나, 멜론
}
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...of
for...in
은 객체의 모든 열거 가능한 속성에 대한 반복for...of
는 컬렉션 전용. 모든 객체보다는 [Symbol.iterable] 속성이 있는 모든 컬렉션 요소에 대해 반복Object.prototype.objCustom = function () {};
Array.prototype.arrCustom = function () {};
let iterable = [3, 5, 7];
iterable.foo = "hello";
for (let i in iterable) {
console.log(i);
// 0, 1, 2, foo, arrCustom, objCustom
}
for (let i of iterable) {
console.log(i); // 3, 5, 7
}