음악, 삶, 개발

for-in 과 for-of 정리 본문

개발 Web/JS

for-in 과 for-of 정리

Lee_____ 2021. 3. 12. 02:02

for 루프를 사용할때마다 항상 헷깔리는것이 for-in 과 for-of 이다.

객체는 in 만 사용할수있으며,

배열은 in 과 of 둘다 사용 가능하다.

// 객체는 in 만 사용 가능.
const obj = { name : 'kim', age : 30 }

for (const key in obj) console.log(key)     // name, age

// 배멸은 in 과 of 를 둘다 사용 가능.
const arr = ['one', 'two']

for (const index in arr) console.log(index) // 0, 1
for (const item of arr) console.log(item)   // one, two