Home > Web Front-end > JS Tutorial > body text

How to use filter function

不言
Release: 2019-02-21 16:08:33
Original
7941 people have browsed it

The arr.filter() function in How to use filter function is used to create a new array from a given array that contains only those elements in the given array that meet the conditions set by the parameter function. Let's take a closer look at how to use filter().

How to use filter function

The basic syntax of filter() is as follows:

var newArray = arr.filter(arg_function[, this_arg])
Copy after login

The parameter of the filter() function is another function that defines each element of the array. Check the conditions. This arg_function itself has three parameters:

array: This is the array in which the .filter() function is called.

index: This is the index of the current element processed by the function.

element: This is the current element that the function is processing.

Another parameter this_arg is used to indicate that the function uses this value when executing the parameter function.

Let’s look at a specific example

The function filter() creates a new array that only contains elements that meet the conditions checked by the isPositive() function.

Example 1:

<!DOCTYPE html>
<html>
<head>
  <title></title>
</head>
<body>

<script> 
function isPositive(value) { 
  return value > 0; 
} 
  
function func() { 
    var filtered = [112, 52, 0, -1, 944].filter(isPositive); 
    document.write(filtered); 
} 
func(); 
</script> 
</body>
</html>
Copy after login

The output result is: 112,52,944

Example 2:

<!DOCTYPE html>
<html>
<head>
  <title></title>
</head>
<body>
<script> 
function isEven(value) { 
  return value%2 == 0; 
} 
  
function func() { 
    var filtered = [11, 98, 31, 23, 944].filter(isEven); 
    document.write(filtered); 
} 
func(); 
</script> 
</body>
</html>
Copy after login

The output result is: 98,944

This article has ended here. For more exciting content, you can pay attention to other related column tutorials on the PHP Chinese website! ! !

The above is the detailed content of How to use filter function. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template