JavaScript Array filter() method
JavaScript Array filter() method
Instance
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>php中文网</title> </head> <body> <p>点击按钮获取数组中大于 18 的所有元素。</p> <button onclick="myFunction()">点我</button> <p id="demo"></p> <script> var ages = [32, 33, 16, 40]; function checkAdult(age) { return age >= 18; } function myFunction() { document.getElementById("demo").innerHTML = ages.filter(checkAdult); } </script> </body> </html>
Run instance»
Click "Run" Example" button to view online examples
Definition and usage
The filter() method creates a new array. The elements in the new array are qualified by checking the specified array. of all elements.
Note: filter() will not detect empty arrays.
Note: filter() does not change the original array.
Browser support
The number in the table indicates the version number of the first browser that supports this method.
Syntax
array.filter(function(currentValue,index,arr), thisValue)
Parameter description
Parameter | Description |
---|---|
function(currentValue, index,arr) | Required. Function, each element in the array will execute this function Function parameters: Parameter description currentValue must be. The value index of the current element is optional. The index value arr of the current element is optional. The array object to which the current element belongs |
thisValue | is optional. The object is used as the execution callback, passed to the function, and used as the value of "this". If thisValue is omitted, the value of "this" is "undefined" |
##Technical details
Returns an array containing all elements that meet the conditions. If there are no matching elements, an empty array is returned. | |
---|---|
1.6 |
Example
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>php中文网</title>
</head>
<body>
<p>点击按钮返回数组 ages 中所有元素都大于输入框指定数值的元素。</p>
<p>最小年龄: <input type="number" id="ageToCheck" value="18"></p>
<button onclick="myFunction()">点我</button>
<p>所有大于指定数组的元素有? <span id="demo"></span></p>
<script>
var ages = [32, 33, 12, 40];
function checkAdult(age) {
return age >= document.getElementById("ageToCheck").value;
}
function myFunction() {
document.getElementById("demo").innerHTML = ages.filter(checkAdult);
}
</script>
</body>
</html>
Run instance»Click the "Run instance" button to view the online instance