본문 바로가기

web/js

[js] for..in 과 for.of의 차이

const post = {
    title : "test",
    content : "Main Article"
}

const array = [1, 2, 3, 4, 5];

for (const iterator in post) {
    console.log(`${iterator}`);
}

// 불가능 
// for (const iterator2 of post) {
//     console.log(iterator);
// }

// 가능
for (const iterator of array) {
    console.log(iterator);
}

 

for in 은 객체의 key를 순차적으로 가져오고 for of는 배열종류에서 사용 가능하며 원소를 순차적으로 가져온다. 

'web > js' 카테고리의 다른 글

[JS] Object.assign  (0) 2023.07.11
[JS] alert, prompt, comfirm  (0) 2023.06.22
[JS] 자료형  (0) 2023.06.16