자바스크립트 배열 필터()
실시예 1
18세 이상인 age[]의 모든 값 배열을 반환합니다.
const ages = [32, 33, 16, 40];
const result = ages.filter(checkAdult);
function checkAdult(age) {
return age >= 18;
}
정의 및 사용
이 filter()
메서드는 함수에서 제공하는 테스트를 통과하는 요소로 채워진 새 배열을 만듭니다.
메서드 는 filter()
빈 요소에 대해 함수를 실행하지 않습니다.
이 filter()
방법은 원래 배열을 변경하지 않습니다.
통사론
array.filter(function(currentValue, index, arr), thisValue)
매개변수
Parameter | Description |
function() | Required. A function to run for each array element. |
currentValue | Required. The value of the current element. |
index | Optional. The index of the current element. |
arr | Optional. The array of the current element. |
thisValue | Optional. Default undefined A value passed to the function as its this value. |
반환 값
유형 | 설명 |
배열 |
테스트를 통과한 요소를 포함합니다. 테스트를 통과한 요소가 없으면 빈 배열을 반환합니다. |
브라우저 지원
filter()
ECMAScript5(ES5) 기능입니다.
모든 브라우저에서 완전히 지원되는 ES5(JavaScript 2009):
Chrome | IE | Edge | Firefox | Safari | Opera |
Yes | 9-11 | Yes | Yes | Yes | Yes |
실시예 2
특정 숫자를 초과하는 age[] 값을 반환합니다.
<p><input type="number" id="ageToCheck" value="30"></p>
<button onclick="myFunction()">Try it</button>
<p id="demo"></p>
<script>
const ages = [32, 33, 12, 40];
function checkAge(age) {
return age > document.getElementById("ageToCheck").value;
}
function myFunction() {
document.getElementById("demo").innerHTML = ages.filter(checkAge);
}
</script>