If you look closely at the sample code you've seen so far, you'll find some of the methods here are unfamiliar. They are map (), filter (), and reduce () functions that are critical to functional programming in any language. They allow you to write more concise code without having to use loops and statements.
The map (), filter (), and reduce () functions form the core of a functional programmer's toolset, which consists of a series of pure, High-order functions, which are the backbone of functional methods. In fact, they are typical of pure functions and higher-order functions, which take a function as input, return an output result, and do not have side effects.
However, they are the implementation criteria for ECMAScript 5.1 in browsers, and they work only in arrays. Each time they are invoked, a new array is created and returned, and the original array is not changed. They are entered as functions and often use anonymous functions as callback functions. They iterate through the array and apply this function to each element of the group!
MyArray = [1,2,3,4];
NewArray = Myarray.map (function (x) {return x*2});
Console.log (myarray); Output: [1,2,3,4]
console.log (NewArray);//output: [2,4,6,8]
Also, they only work on arrays and cannot be used for other data structures that can be iterated, such as objects. Don't worry, there are a lot of libraries like underscore.js,lazy.js,stream.js and so on that have implemented their own more powerful maps (), filter () and reduce ().
Callback
If you've never used a callback before, the concept may be confusing to you. JavaScript, in particular, gives you several ways to declare a function.
Callback functions are used to pass to another function for their use, which is a way of passing logic like an object:
var myarray = [1,2,3];
function Mycallback (x) {return x+1};
Console.log (Myarray.map (mycallback));
For simpler tasks, you can use anonymous functions:
Console.log (Myarray.map (function (x) {return x+1}));
Callbacks are not just for functional programming, they can do a lot of things in JavaScript. For example only, there is a callback () function for the Ajax invocation of jquery:
function Mycallback (XHR) {
console.log (xhr.status);
return true;
}
$.ajax (Myuri). Done (Mycallback);
Note that only the name of the function is used here, because we are not going to call the function but pass the function, which is wrong:
$.ajax (Myuri). Fail (Mycallback (XHR));
or
$.ajax (Myuri). Fail (Mycallback ());
What happens if we call a function? In this case, Mycallback (XHR) will try to execute, the console will print "Undefined" and return true. When Ajax () completes the call, the callback function it finds based on the name will be a "true" and the error will be given.
That means we can't specify what parameters to pass to the callback function, and if our callback function needs to pass the Ajax () function to the parameters we want, we can wrap the back function in an anonymous function:
function Mycallback (status) {
console.log (status);
return true;
}
$.ajax (Myuri). Done (function (XHR) {
mycallback (xhr.status)
});
Array.prototype.map ()
Map () is the eldest of these functions, and it simply applies the callback function to the elements in the array.
Syntax: Arr.map (callback [, Thisarg]);
Parameters:
callback (): This function generates an element for the new array, which receives the parameter: ◦currentvalue: The element to which the array is currently traversed
◦index: The current element ordinal in an array
◦array: The array currently being processed
Thisarg: This is an optional parameter, and it acts as the callback function when the callback is executed.
Example:
var
integers = [1,-0, 9,-8, 3],
numbers = [1, 2, 3, 4],
str = ' Hello world, ya doing? ';
Maps integers to their own absolute value
console.log (Integers.map (Math.Abs));
Multiplies the elements in an array by their position ordinal
console.log (Numbers.map (function (x, i) {return
x * I
});
Each word is changed to one uppercase
Console.log (Str.split ("). Map (function (s, i) {
if (i% 2 = 0) return
s.touppercase ();
else return
s;
});
Although the Array.prototype.map method is the standard method of array objects in JavaScript, you can also easily extend your own objects.
MyObject.prototype.map = function (f) {return
new MyObject (f (this.value));
Array.prototype.filter ()
The filter () function is used to filter out some elements in an array. The callback function must return True (keep to the new array) or fake (throw away). A map () can do similar things by returning elements that you like to throw away as null, but the filter () function removes these elements from the new array instead of leaving a null position.
Syntax: Arr.filter (callback [, Thisarg]);
callback (): This function is used to test each element in the array, to keep the return true, otherwise return false. It has these parameters: ◦currentvalue: The element that the array is currently traversing to
◦index: Ordinal of the current element in an array
◦array: The array currently being processed
Thisarg: This is an optional parameter, and it acts as the callback function when the callback is executed.
Example:
var myarray = [1, 2, 3, 4]
words = ' Hello 123 world how 345 ya doing '. Split (");
re = ' [A-za-z] ';
Filter integer
console.log ([-2,-1, 0, 1, 2].filter (function (x) {return
x > 0
}));
Filter all words containing letters
Console.log (Words.filter (function (s) {return
s.match (re);
});
Randomly moves the element
Console.log (Myarray.filter () (function () {return
Math.floor (Math.random () * 2)}) in the divisor group
;
Array.prototype.reduce ()
The reduce () function, sometimes called fold, is used to bring together all the values in an array. The callback needs to return the logic of the grouped object. For numbers, they tend to be added together or multiplied together. For strings, they are often appended together.
Syntax: Arr.reduce (callback [, InitialValue]);
Parameters
callback (): This function merges two objects into one object and returns them. Parameters are: ◦previousvalue: The value returned when the last callback function was invoked, or the initial value (if any)
◦currentvalue: Elements currently being processed by the array
◦index: Ordinal of the current element in an array
◦array: The array currently being processed
initialvalue: Optional. First callback the initial value of the incoming parameter
Example
var numbers = [1, 2, 3, 4];
Add all the values in the array
console.log ([1, 2, 3, 4, 5].reduce (function (x, y) {return
x + y
}, 0));
Finds the largest value in an array
console.log (Numbers.reduce (function (A, b) {return
Math.max (A, B)//MAX () function can have only two parameters
}
) ;
Other functions
The map (), filter (), and reduce () functions are not alone in the toolbox of our helper functions. There are many more functions that can be used in almost all functional applications.
Array.prototype.forEach
The ForEach () function is essentially a non-pure version of the map () function that iterates through the entire array and applies callbacks to each element. However, these callback functions do not return a value. It is a more pure way of implementing a For loop.
Syntax: Arr.foreach (callback [, Thisarg]);
Parameters:
callback (): applied to each element in the array. Parameters are: ◦currentvalue: Elements currently being processed in the array
◦index: Ordinal of the current element in an array
◦array: the array being processed
thisarg: Optional. Value as this in the callback function
Example:
var arr = [1, 2, 3];
var nodes = Arr.map (function (x) {
var elem = document.createelement ("div");
elem.textcontent = x;
return elem;
});
Outputs a log
Arr.foreach (function (x) {
console.log (x)
}) for
each element's value; Appends the node to the DOM
Nodes.foreach (function (x) {
document.body.appendChild (x)
});
Array.prototype.concat
If you do not use a for or while processing array, you will often need to concatenate the array. Another JavaScript built-in function concat is dedicated to doing this. The Concat function returns a new array without changing the old array. It can stitch together all the parameters you pass in.
Console.log ([1, 2, 3].concat ([' A ', ' B ', ' C '])//Stitching two arrays
Output: [1, 2, 3, ' A ', ' B ', ' C ']
It returns an array of two arrays, while the original ones are not changed. This means that the concat function can be chained to a call.
var arr1 = [1,2,3];
var arr2 = [4,5,6];
var arr3 = [7,8,9];
var x = Arr1.concat (arr2, ARR3);
var y = arr1.concat (arr2). Concat (ARR3));
var z = arr1.concat (Arr2.concat (ARR3)));
Console.log (x);
Console.log (y);
Console.log (z);
The values for variables x, y, and Z are finally [1,2,3,4,5,6,7,8,9].
Array.prototype.reverse
This JavaScript built-in function is used for array morphing. The reverse function is used to invert an array, which means that the first element will run to the end, and the last element is the one.
However, this function does not return a new array, but instead replaces the original array. We can do a better job. The following is a pure inverse array function
var invert = function (arr) {return
Arr.map (function (x, I, a) {return
a[a.length-(i + 1)];
})
; var q = Invert ([1, 2, 3, 4]);
Console.log (q);
Array.prototype.sort
Like the map (), filter (), and reduce () functions, the Sort function sort () needs to pass in a callback function to define how the array is sorted. However, like reverse (), it also replaces the original array. That's not very good.
arr = [200, 12, 56, 7, 344];
Console.log (Arr.sort (function (a,b) {return a–b}));
ARR is now: [7, 12, 56, 200, 344];
We can write a pure function of sort (), but the sorting algorithm's source code is cumbersome. For particularly large arrays, appropriate algorithms should be chosen based on specific data structures, such as fast sorting, merge sorting, bubble sorting, and so on.
Array.prototype.every and Array.prototype.some
Array.prototype.every () and Array.prototype.some () are pure high-order functions that are methods of the array object and are tested by a callback function based on the Boolean value returned by each element of the array (or equivalent to a Boolean value). If all elements in the array return true through the callback function evaluation, the Every () function returns True, and returns True if an element in the array returns the True,some () function.
Example:
function Isnumber (n) {return
!isnan (parsefloat (n)) && isfinite (n);
}
Console.log ([1, 2, 3, 4].every (Isnumber)); Return:true
Console.log ([1, 2, ' a '].every (isnumber));//Return:false
Console.log ([1, 2, ' a '].some ( Isnumber)); Return:true