Filter is also a common operation, it is used to Array
filter out some of the elements, and then return the remaining elements.
and map()
Similarly, Array
filter()
a function is also received. And the map()
difference is that the filter()
incoming function acts on each element in turn, and then whether true
false
the element is persisted or discarded based on the return value.
For example, in one Array
, delete an even number, keep only the odd number, and you can write:
var arr = [1, 2, 4, 5, 6, 9, 10, 15];var r = arr.filter(function (x) { return x % 2 !== 0;});r; // [1, 5, 9, 15]
Delete the Array
empty string in one, so you can write:
var arr = [‘A‘, ‘‘, ‘B‘, null, undefined, ‘C‘, ‘ ‘];var r = arr.filter(function (s) { return s && s.trim(); // 注意:IE9以下的版本没有trim()方法});r; // [‘A‘, ‘B‘, ‘C‘]
filter()
the key to using this higher-order function is to implement a "filter" function correctly.
callback function
filter()
The received callback function can actually have multiple parameters. Usually we use only the first parameter, which represents an Array
element. The callback function can also receive two additional parameters, representing the location of the element and the array itself:
var arr = [‘A‘, ‘B‘, ‘C‘];var r = arr.filter(function (element, index, self) { console.log(element); // 依次打印‘A‘, ‘B‘, ‘C‘ console.log(index); // 依次打印0, 1, 2 console.log(self); // self就是变量arr return true;});
Using filter
, can subtly remove Array
the repeating elements:
JS Basic (2) filter filter ()