[TIL] METHOD

j1_0·2022년 12월 7일

DAY 27 <배열의 메소드>

배열의 메소드

forEach

배열의 값들을 하나씩 꺼내서 반복하는 것이다.
함수를 넣는 방법과 함수를 변수에 담아서 넣는 방법이 있다.

const testArr = [2,10,100,7,71,50,27,1]
testArr.forEach(callbackfn(함수));
//함수를 담은 변수 // 매개변수는 함수의 형태여야한다.
const testfunc = function(){
console.log("hello JavaScript");
} 
testArr.foreEach(testArr);

testArr.forEach(function(){
console.log("hello JavaScript");
});// (hello javaScript )*8

testAff.forEach(function(item){
console.log(item);
}); // 2 10 100 7 71 50 27 1
//////////////////////////////////////////////
testArr.forEach((item)=>{
console.log(item)
});

map

배열의 값들을 꺼낸뒤 리턴한 값들을 새로운 배열을 만들어 반환하는 것이다.

여러번 사용하지 않아 주로 익명함수로 사용한다.

const testArr = [2,10,100,7,71,50,27,1]

testArr.map(function(item){
console.log(item);
});

const mappedArr = testArr.map(function(item){
return "응";
});

console.log(mappedArr); //[
  '응', '응', '응',
  '응', '응', '응',
  '응', '응'
]



const mappedArr = testArr.map(function(item){
return item;
});

console.log(mappedArr); //[
  2,10,100,7
71,50,25,1
]

const mappedArr = testArr.map(function(item){
return item*2;
});
//////////////////////////////////
const mappedArr = testArr.map((item)=> item *2
); //function, return (한줄일 시) 생략가능

filter

말 그대로 거르는 것이다.
filter에는 항상 조건이 들어가고 그 조건에 맞게 걸러내어진 값을 반환한다.

const testArr = [2,10,100,7,71,50,27,1]

test.Arr.filter((item)=>{
console.log(item) 
}); //2 10 100 7 71 50 27 1

const fillteredarr = testArr.filter((item)=>{
if(item >10) {
return item;
} else{
return null;
}
}); //[71, 50, 27, 1

1개의 댓글

comment-user-thumbnail
2022년 12월 8일

고생많으셨습니다 ㅎㅎ

답글 달기