본문 바로가기
Development (국비 복습 )/JavaScript

array.forEach() , map()

by Puddingforever 2022. 9. 28.

forEach()

callback 함수를 불러낸다 

const numbers = [45,4,9,16,25]; //배열 생성
let text = "";
numbers.forEach(myFunction);

function myFunction(value, index, array) {
txt += value + "<br>";
}



함수는 3개의 인자(argument)를 갖는다

-아이텝 값
-인텍스 값
-배열

하지만 위의 배열을 forEach()로 돌릴 때 값만 가지고 움직이기 때문에
아래와 같은 함수로 써도 괜찮다

function myFunction(value){

txt += value + "<br>";
}



map()

https://www.freecodecamp.org/korean/news/javascript-map-method/

어떤 배열에 있는 모든 요소들의 갑을 변경해서 만드 새로운 배열을 써야할 때 사용
하지만 원본 배열을 바꾸진 않는다.

let = arr = [3,4,5,6];

위의 배열의 각 요소에 3을 곱해야한다고 상상해보자
다음과 같이 for루프를 사용할 수도 있다

let arr = [3,4,5,6];
for(let i=0;i<arr.length;i++){
arr[i] = arr[i]*3;
}

console.log(arr); // [9,12,15,18]




그러나 사실 , map() 메소드를 사용하면 동일한 결과를 얻을 수 있다.

let arr = [3,4,5,6];
let modifiedArr = arr.map(function(element){
return element*3;
});

console.log(modifiedArr);; // [9,12,15,18]



함수를 따로 빼서 쓸 수도 있다.

const numbers1 = [45,4,9,16,25];
const numbers2 = numbers1.map(myFunction);

function myFunction(value){
return value * 2;
}



'Development (국비 복습 ) > JavaScript' 카테고리의 다른 글

this키워드와 slice()  (2) 2023.02.07
event.target  (0) 2022.10.01
The Fisher Yates Method 셔플 알고리즘  (0) 2022.09.26
비교 함수 compare function  (0) 2022.09.26
splice  (0) 2022.09.26

댓글