Home > Article > Web Front-end > Is filter an es6 method?
filter is an es6 method. filter() is a new array method in es6, used to filter array elements; this method will pass the array elements into a callback function, in the callback function it will be judged whether the element meets the specified conditions, and if it does, it will be returned. The syntax is "arr. filter(callback function, thisValue)".
The operating environment of this tutorial: Windows 7 system, ECMAScript version 6, Dell G3 computer.
filter() is a new array method added in es6, which is used to filter array elements and return elements in the array that meet specified conditions.
The filter() method will pass the array elements into a callback function. In the callback function, it will determine whether the element meets the specified conditions and return if it meets the specified conditions.
Syntax:
arr.filter(回调函数,thisValue)
Callback function: Each element in the array will execute this function to specify conditions and process elements
thisValue: 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"
Format of the callback function:
function callbackfn(Value,index,array)
Accepts up to three parameters:
value: The value of the current array element, cannot be omitted.
index: The numeric index of the current array element.
array: The array object to which the current element belongs.
Return value: is a new array containing all values for which the callback function returns true. If the callback function returns false for all elements of array , the length of the new array is 0.
Example 1: Return all even numbers
var a = [2,3,4,5,6,7,8]; function f (value) { if (value % 2 == 0) { return true; }else{ return false; } } var b = a.filter(f); console.log(b);
Output result:
Example 2: Return All leap years
var a = [1995,1996,1997,1998,1999,2000,2004,2008,2010,2012,2020]; function f (value) { if(value%4==0 && value%100!=0){ return true; } else { return false; } } var b = a.filter(f); console.log(b);
Output results:
[Related recommendations:javascript video tutorial,web front-end】
The above is the detailed content of Is filter an es6 method?. For more information, please follow other related articles on the PHP Chinese website!