1. Usage of reduce function:
$ (function () {//arrowmouseover ();Array.prototype.reduce=NULL; Set the built-in reduce function to nullvarEleresult=document.getelementbyid ("result"); Console.log=function (Result) {vartext=document.createTextNode (Result); varBr=document.createelement ("BR"); //var name=document.createattribute ("Data-name");eleresult.appendchild (text); Eleresult.appendchild (BR); //Br.setattribute (name, "Zhu"); }; if(typeofarray.prototype.reduce!="function") {Array.prototype.reduce=function (callback,initialvalue) {//Custom reduce functionvarprevious=initialvalue,k=0, length= This. Length; if(typeofinitialvalue==="undefined"{//If the initial value is not passed in, previous equals the first element of the array previous= This[0]; K=1; } if(typeofcallback==="function"){ for(k;k<length;k++){ This. hasOwnProperty (k) && (Previous=callback (Previous, This[K], This)) } } returnprevious; } } varsum=[1,2,3,4].reduce (function (previous,current,array) {returnprevious+Current ; }); Console.log (sum);//10varmatrix=[ [1,2],[3,4],[5,6] ]; varflattn=matrix.reduce (function (previous,current) {returnPrevious.concat (current); }); Console.log (FLATTN);//[1, 2, 3, 4, 5, 6]
});
Note: the reduce () function, which implements the cumulative function of an array, needs to pass a callback function and an initial value of InitialValue,
Suppose the callback function has an incoming parameter, prev and Next,index, and an array. Prev and next you have to understand.
Generally speaking, Prev starts with the first element in the array, and next is the second element.
But when you pass in the initial value (InitialValue), the first prev will be the first element in the array, and if the initial value is not passed in, the first element of the array is taken as the initial value.
function Person (name,age) { This. name=name; This. age=Age ; Alert ("My name is"+arguments[0]+", age is"+ arguments[1]); This. sayhello=function () {alert ("Hello"); }}function Student (name,age,stuid,classid) {person.apply ( This, arguments); This. studentid=Stuid; This. classid=ClassID;}varperson1=NewPerson ("Zhu", at);varstudent1=NewStudent ("STU1", A,1001,1);
Note: The student object inherits the person object, only need to add one in the Student object, Person.apply (this,arguments), but only when instantiated, can see the effect.
JavaScript Essay--function usage