The array method is quite numerous, but it is possible to use the foreach,splice and slice contact more, filter () to tell the truth before not too much understanding. In fact, the filter () array provides filtering functionality that iterates through all the elements of the array and returns the element that satisfies the condition, as follows:
First-bit formal parameters
var arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];var arr2 = Arr.filter (function (x) {return x >= 8;}); Console.log (ARR2); [8, 9, 10]
What the above code does is to compare each element in arr with 8 to get a 8,9,10. The first parameter x represents the elements in the array.
Second-bit formal parameter
Let's take a look at the following code:
var arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];var arr2 = Arr.filter (function (x, index) {return index% 3 = = 0 | | x >= 8;} ); Console.log (ARR2); [1, 4, 7, 8, 9, 10]
Index is the index of the array, which is the loop process, first passing in element 1, its index is 0, and 0%3===0, satisfies the condition.
The second pass is 2 and the index is 1, but 1%3! ==0, and 1:8 small, so is ruled out, in turn, to obtain the output of our arr2.
Third-parameter
Let's look at a piece of code and combine the filter with the array to weigh
var arr = [1, 2, 2, 3, 4, 5, 5, 6, 7, 7];var arr2 = Arr.filter (function (x, index,self) {return self.indexof (x) ===index;}) ; Console.log (ARR2); [1, 2, 3, 4, 5, 6, 7]
How is this implemented, the third parameter of filter is the function itself, and indexof always returns the index that matches that element for the first time , so let's go through the traversal process.
For the first loop, the index of the incoming element 1,index (1) is 0, and at this point 1 of the index is 0,ok, which is satisfied.
In the second loop, the index of the incoming element 2,index (2) is 1, and at this point the index of 2 is also 1,ok and satisfied.
In the third loop, the index of the incoming element 2,index (2) is 1, and at this point the index of 2 is 2,ok, not satisfied, is pass, here is the ingenious borrowing indexof always find the first occurrence of the position.
Summarize
Filter (x,index,self) provides an array of filtering capabilities, where x represents an element, and index is the one that passes in the element with X, and self represents the array itself.
That's all there is to it.
Array filter () parameter in detail, skillfully use the filter () array to weight