const list = [1, 2, 3];
for (var i = 0; i < list.length; i++) {
log(list[i])
}
// 1
// 2
// 3
const str = 'abc';
for (var i = 0; i < str.length; i++) {
log(str[i])
}
// a
// b
// c
for (const a of list) {
log(a)
}
for (const a of str) {
log(a)
}
// 조금 더 간결하게 변경해서 동일한 결과를 도출
<aside> 💡 간결하게 만든 것 이상의 의미가 있을까?
</aside>
<aside> 💡 ES6에서 for of 문이 어떻게 동작하고 어떤 방식으로 추상화하는지 알아보자
</aside>
const arr = [1, 2, 3];
arr[0] // 1
arr[1] // 2
arr[3] // undefined
const set = new Set([1, 2, 3])
set[0] // undefined
set[1] // undefined
const map = new Map([['a', 1], ['b', 2], ['c', 3]])
map[0] // undefined
map[1] // undefined
<aside> 💡 set과 map에서 위와 같이 접근이 안된다는 것은 for문을 사용해서 순회할 수 있는 방식으로 구성이 되지 않았다는 것을 뜻한다
</aside>
<aside> 💡 아래와 같이 console.log(arr)를 해보면 key값에 맞는 value를 순회할 수 있었지만 set, map에서는 불가능했기 때문에 for …of 메소드는 이런 방식을 사용하지 않는 다는 것을 알 수 있다
</aside>