function ForEach (array,action) { for(varI=0; i<array.length;i++) Action (Array[i]);} function reduce (combine,Base, Array) {ForEach (Array,function (element) {Base=combine (Base, Element);}) return Base;} function Countzeroes (array) {function counter (total,element) {returntotal+ (element===0?1:0); } returnReduce (counter,0, array);} Console.log (Countzeroes ([0, at, About,0,0]))
3
"Attribution function"
Of the above three functions, the first FOreach () implements the traversal of an array and anction () operations on each of these elements.
a second Reduce (), or fold, converts an array to a single value by repeatedly invoking a function//(the function adds each element of the array to a base value).
The three parameters of the imputation function are-- the function to be executed, the cardinality, the array (the order is mainly based on the habit problem).
a third The function computes the number of 0 elements in the array, and solves the problem by repeating whether the elements of the array are 0. Therefore, you can choose the attribution function. The corresponding three parameters, respectively-counter () function, 0,array.
Where counter uses the conditional operator and the value equals 0, the cardinality is added to one.
Alternatively, an algorithm function count can be defined for use by Countzeros.
functionForEach (array,action) { for(vari=0;i<array.length;i++) Action (Array[i]);}functioncount (test,array) {varCounted=0; ForEach (Array,function(Element) {if(test Element) counted++; })
return counted;}functioncountzeroes (array) {functionIszero (x) {returnX===0;} The entire function acts as the return value and is passed as the if criterion. The return value is true/false because the function itself is a comparison parameter of 0. returncount (Iszero,array);}
Console.log (Countzeroes ([0,23,56,0,0]))
3
" map Array "
The so-called mapping refers to the ability to iterate through an array and apply the function to each element (such as foreach). But instead of discarding the function return value, he re-establishes a new array with these return values.
The function count (), which is used to test whether the elements in the array conform to test conditions, and the statistics plus one.
The function Countzeros (), which accepts an array of parameters, that is, tests. and define the method in which the test Test=iszero "because the method is only meaningful to the Countzeros () function, it is defined within the function body. Others, such as count (), are defined separately because their parameters have a more abstract universal meaning. For repeated use "
function Map (func,array) { var result=[]; ForEach (array,function(element) { Result.push (func (Element)); } ) return result;} Console.log (Map (math.round,[0.09,2,3.4,9.4, Math.PI])); [0, 2, 3, 9, 3]
reduce& Map Array Map (note)