Return an array of all values in ages[] that are 18 or over:
const ages = [32, 33, 16, 40];
const result = ages.filter(checkAdult);
function checkAdult(age) {
return age >= 18;
}
Try it Yourself »
The filter()
method creates a new array filled with elements that pass a test provided by a function.
The filter()
method does not execute the function for empty elements.
The filter()
method does not change the original array.
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. |
Type | Description |
Array | An array of elements that pass the test. An empty array if no elements pass the test. |
Return the values in ages[] that are over a specific number:
<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>
Try it Yourself »
filter()
is an ECMAScript5 (ES5) feature.
ES5 (JavaScript 2009) fully supported in all browsers:
Chrome | Edge | Firefox | Safari | Opera | IE |
Yes | Yes | Yes | Yes | Yes | 9-11 |
截取页面反馈部分,让我们更快修复内容!也可以直接跳过填写反馈内容!