for이 있는데 forEach 쓰는이유
for문보다 성능은 안좋은데, 배열매소드는 연달아 썼을때 편리하다.
그중 가장 대표적인게 map이라는 메서드
map도 forEach랑 비슷하게 반복문 역활을 해주는데 한가지 기능을 더 해줌
const array = [1, 2, 3, 4];
const result = [];
for (let i = 0; i < 4; i++){
result.push(array[i]*2);
}
result
// [2, 4, 6, 8];
------------------------------------------------------
array.map((element, i) => {
return element * 2
})
// [2, 4, 6, 8];
array
// [1, 2, 3, 4] map 기존배열은 안바뀐다
forEach와 map쓰는 이유
Array(9)
// [empty * 9]
Array(9).fill()
// [undefined,undefined,undefined,undefined,undefined,undefined,undefined,undefined,undefined]
Array(9).fill(0)
// [0, 0, 0, 0, 0, 0, 0, 0, 0]
Array(9).fill().map((element, index) => {
return index + 1;
})
// [1, 2, 3, 4, 5, 6, 7, 8, 9]
'javascript' 카테고리의 다른 글
함수형 프로그래밍과 자바스크립트 그리고 이터러블/이터레이터 프로토콜 (3) | 2025.04.30 |
---|---|
History api (pushState, replaceState) (0) | 2023.07.17 |
textContent , innerText 차이 (0) | 2022.04.09 |
i++와 i+=1의 차이점? (0) | 2022.04.05 |
HTMLCollection vs NodeList (0) | 2022.04.01 |