Higher-order functions are called Higher-order function in English. JavaScript functions actually point to a variable. Since the variable can point to a function, the function's arguments can receive the variable, then one function can receive another function as a parameter, which is called the higher order function.
One of the simplest high-order functions:
function Add (x, Y, f) { return f (x) + f (y);}
When we call add(-5, 6, Math.abs)
, arguments x
, y
and f
respectively receive -5
, 6
and function, according to the Math.abs
function definition, we can deduce the calculation process as:
x =-5= 6=+ f (y) ==> Math.Abs ( -5) + math.abs (6) ==> one; return 11;
Map
For example, if we have a function f (x) =x2, to put this function on an array [1, 2, 3, 4, 5, 6, 7, 8, 9]
, it can be map
implemented as follows:
Because the map()
method is defined in JavaScript Array
, we call Array
the map()
method, passing in our own function, and get a new Array
result:
function Pow (x) { return x * x;} var arr = [1, 2, 3, 4, 5, 6, 7, 8, 9// [1, 4, 9, +, +, +, +, +, Bayi]
map()
The parameters passed in are, that is pow
, the function object itself.
You might think, no need map()
, write a loop, or you can calculate the result:
var function (x) { return x * x;}; var arr = [1, 2, 3, 4, 5, 6, 7, 8, 9]; var result = []; for (var i=0; i<arr.length; i++) { Result.push (f (arr[i]));}
Yes, but, from the loop code above, we can't see at a glance "put f (x) in each element of the array and generate a new array".
So, map()
as a higher-order function, it actually abstracts the arithmetic rules, so we can calculate not only the simple f (x) =x2, but also any complex function, such as converting Array
all the numbers to strings:
var arr = [1, 2, 3, 4, 5, 6, 7, 8, 9// [' 1 ', ' 2 ', ' 3 ', ' 4 ', ' 5 ', ' 6 ', ' 7 ', ' 8 ', ' 9 ']
Reduce
Let's look at the usage of reduce. Array of reduce()
a function on this Array
[x1, x2, x3...]
, the function must receive two parameters, the reduce()
results continue and the next element of the sequence to do the cumulative calculation, the effect is:
[X1, x2, X3, x4].reduce (f) = f (f (f (x1, x2), x3), x4)
For example, to a Array
sum, you can use the reduce
implementation:
var arr = [1, 3, 5, 7, 9];arr.reduce (function (x, y) { return x +//
Filter
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, ten,]; var r = Arr.filter (function (x) { return x% 2!== 0// [1, 5 , 9, []
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 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 ( element, index, self) { // print ' A ', ' B ', ' C ' // print 0, 1, 2 // self is the variable arr return True;});
Sort sorting algorithm
Sorting is also an algorithm that is often used in programs. Whether you use bubble sorting or fast sorting, the core of the sort is to compare the size of the two elements. If it's a number, we can compare it directly, but what about a string or two objects? There is no point in directly comparing the size of mathematics, so the process of comparison must be abstracted by functions. It is generally stipulated that for two elements and, if considered, then returned, if considered, then returned, x
y
x < y
-1
x == y
0
If considered x > y
, then returned 1
, so that the sorting algorithm does not care about the specific comparison process, Instead, they are sorted directly by comparison results.
JavaScript's Array
sort()
approach is for sorting, but the sort results can be a surprise to you:
// The result looks normal: // [' Apple ', ' Google ', ' Microsoft ']; // Apple is at the bottom of the line: // [' Google ', ' Microsoft ', ' apple '] // an incomprehensible result: // [1, 2, ten]
The second sort apple
is ranked last because the strings are sorted according to the ASCII code, while a
the ASCII code of the lowercase letters is after the uppercase letters.
What the hell is the third sort of result? Can a simple numeric order be wrong?
This is because Array
the sort()
method defaults to converting all elements to string reordering, and the results are ‘10‘
in ‘2‘
front of them because the characters ‘1‘
‘2‘
are smaller than the ASCII code of the characters.
If you do not know sort()
the default collation of the method, sort the numbers directly, absolutely planted in the pit!
Fortunately, the sort()
method is also a higher-order function, and it can also receive a comparison function to implement a custom sort.
To sort by numerical size, we can write this:
var arr = [Ten, 1, 2];arr.sort (function (x, y) { if (x < y) {
return -1; } if (x > y) { return 1; } return 0// [1, 2, ten,]
If you want to sort in reverse order, we can put the large number in front:
var arr = [Ten, 1, 2];arr.sort (function (x, y) { if (x < y) {
return 1; } if (x > y) { return -1; } return 0// [Ten, 2, 1]
By default, the string is sorted by the size of ASCII, and now we propose that the sort should be ignored in case, sorted alphabetically. To implement this algorithm, you do not have to change the existing code, as long as we can define the ignoring case of the comparison algorithm can be:
var arr = [' Google ', ' apple ', ' Microsoft '];arr.sort (function (s1, S2) { = S1.touppercase (); = s2.touppercase (); if (X1 < x2) { return -1; } if (X1 > x2) { return 1; } return 0// [' Apple ', ' Google ', ' Microsoft ']
Ignoring the case to compare two strings is actually the first to capitalize the strings (or all lowercase) before comparing them.
As you can see from the above example, the abstraction of higher-order functions is very powerful, and the core code can be kept very concise.
Finally, the sort()
method will be modified directly, Array
it returns the result is still the current Array
:
var a1 = [' B ', ' A ', ' C ']; var a2 =// [' A ', ' B ', ' C ']// [' A ', ' B ', ' C ']// True, A1 and A2 are the same object
07.javascript--Getting Started higher order functions