Working with arrays using functions

Why use functions to work with arrays? Take an example to know.
Suppose there is an array with numbers in it. How to calculate the average?
First non-functional programming.
var a = [1,1,3,5,5];
var b = 0;
for(var i=0;i<a.length;i++){
b+=a[i];
}
var c = b/a .length;
console.log(c);//The result is 3;
this doesn't look concise.
The same calculation can be done using the array method reduce().
var sum = function(x,y)
{ return x+y };
var a = [1,1,3,5,5];
var c = a.reduce(sum)/a.length;
console.log(c );//The result is also 3
, which looks more concise. If multiple arrays calculate the same value, the same function can be used to reduce the amount of code.
Another example. Find the standard deviation of an array (first calculate the square of the difference after subtracting the mean for each data, and then sum) The sum
has been summed above;
var sun = function(x,y){return x+y};
var square = function(x) {return x*x};
var a = [1,1,3,5,5];
var b = a.reduce(sum)/a.length;
var c = a.map(function(x) {return xb});
var d = Math.sqrt(c.map(square).reduce(sum)/ a.length);
console.log(d);//The result is 1.78888
. A map() function is also used here. to perform this calculation.

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326680608&siteId=291194637