개발노트/Javascript

(JS) filter() (2019/10/14)(보충필요!)

superpil 2019. 10. 14. 18:22

-개념

배열의 한 바퀴 돌면서 걸러내는 메서드이다.

 

array.filter(callbackFunction(element, index, array){})

1. element

배열을 순회하면서 배열의 값을 출력한다.

 

2. index

배열을 순회하면서 인덱스 번호를 출력한다.

 

3. array

배열의 length만큼 배열 전체 값을  출력한다.

 

 

-사용방법

1. 짝수 걸러내기

let numberArry = [1,2,3,4,5,6,7,8,9,10];

let filterArry = numberArry.filter(function(element){
    return element % 2 === 0;
})

console.log(filterArry); // [2, 4, 6, 8, 10] 출력

let filterArry = numberArry.filter(function(element){
    return element % 2 === 0;
})

let numberArry의 element를 한 개씩 가져와서 2로 나눴을 때 0으로 떨어지면 let filterArry에 담는다.

filter()의 return은 true일 때 요소들을 모아서 새로운 배열에 담는다. 만약, return을 생략하게 되면 undefined이니깐 false이다. 따라서, 빈 배열을 출력시킨다.