Home  >  Article  >  Web Front-end  >  What is the usage of filter in javascript

What is the usage of filter in javascript

藏色散人
藏色散人Original
2021-10-29 14:39:1615562browse

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)...)".

What is the usage of filter in javascript

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

What is the usage of filter in javascript

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:

What is the usage of filter in javascript

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Previous article:what does javascript doNext article:what does javascript do