
⭐forEach
forEach는 array를 순회하는 함수이며, 인자로 함수를 받아 각 배열 요소에 해당 함수를 적용한다.
const num = [123,456,789,10];
num.forEach((number) => {
console.log(number) // 123,456,789,10
});
⭐for of (es6)
for of는 array만 사용 가능한 forEach와는 달리 array와 obj 모두 사용가능하다.
(순회 가능한(iterable) 객체에 사용이 가능하다.)
const weather = ["sunny","clear"]
for(let sky of weather){
console.log(sky) // sunny , clear
}
⭐for in
for in은 모든 객체에 사용이 가능하다.
또한 상위 prototype의 값을 포함한다는 차이점이 있으며, 확장 속성까지 순회할 수 있으니 주의해야한다.
const weather = ["sunny","clear"]
Array.prototype.getIndex = "rain";
for(let sky in weather){
console.log(weather[sky]) // sunny , clear, rain
}
for(let sky of weather){
console.log(sky) // sunny , clear
}
'코딩 > javascript' 카테고리의 다른 글
📕ES6 주요 문법 정리 (0) | 2021.05.25 |
---|