The function of filter in JavaScript is to create a new array, and the elements in the new array are checked by checking all the elements that meet the conditions in the specified array. The usage syntax is "array.filter(function(currentValue,index ,arr)...)".
The operating environment of this article: Windows 7 system, javascript version 1.8.5, DELL G3 computer
What is the usage of filter in javascript?
The filter() method creates a new array. The elements in the new array are checked by checking all elements in the specified array that meet the conditions.
Note: filter() will not detect empty arrays.
Note: filter() does not change the original array.
Syntax
array.filter(function(currentValue,index,arr), thisValue)
Parameter description
Example:
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title></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>
The effect is as follows:
Recommended study: "javascript basic tutorial"
The above is the detailed content of What is the usage of filter in javascript. For more information, please follow other related articles on the PHP Chinese website!