js filter() method

The filter() method tests all elements using the specified function and creates a new array containing all elements that pass the test.

    filter() basic syntax:
       arr.filter(callback[, thisArg])

   filter() parameter introduction:
      Parameter name description
      callback A function to use to test each element of the array. Called with parameters (element, index, array)
      Return true to keep the element (passing the test), false to not keep it.
      thisArg is optional. The value used for this when the callback is executed.

  filter() usage description:

    filter calls the callback function once for each element in the array, and creates a new array with all elements for which callback returns true or a value equivalent to true.
    The callback will only be called on indexes that have been assigned, and will not be called for indexes that have been deleted or have never been assigned. Elements that do not pass the callback test will be skipped and will not be included in the new array.

    callback is called with three parameters:

    the value of the element
    the index of the element
    the array being traversed
    If a thisArg parameter is provided to filter, it will be used as the value of this when the callback is called. Otherwise, the this value of the callback will be the global object in non-strict mode and undefined in strict mode.

    filter does not change the original array.

    The range of elements that filter traverses is determined before the callback is called for the first time. Elements added to the array after calling filter will not be traversed by filter.
    If existing elements have been changed, the value they pass into the callback is the value at the moment the filter traversed to them. Elements that are deleted or never assigned a value are not traversed. 

Example:

/*
filter() example: filter to exclude all small values

The following example uses filter to create a new array consisting of elements in the original array with values ​​greater than 10.

*/

function isBigEnough(element) {
return element >= 10;
}
var filtered = [12, 5, 8, 130, 44].filter(isBigEnough);

console.log(filtered);//[ 12, 130, 44 ]

 

 

/*
  filter() compatible legacy environment
  filter was added to ECMA-262 standard version 5 and is therefore not supported in some implementation environments. This can be solved by inserting the following code at the beginning of the script,
  which allows it to be used in implementations that do not natively support filter. The algorithm is the one specified in ECMA-262 5th edition
*/

Array.prototype.filter = Array.prototype.filter || function(func) {
var arr = this;
var r = [];
for (var i = 0; i < arr.length; i++) {
if (func(arr[i],i,arr)) {
r.push(arr[i]);
}
}
return r;
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324932757&siteId=291194637