標籤:
1、reduce函數用法:
$(function(){ // arrowMouseOver(); Array.prototype.reduce=null; //將內建reduce函數設定為null var eleResult=document.getElementById("result"); console.log=function(result){ var text=document.createTextNode(result); var br=document.createElement("br"); //var name=document.createAttribute("data-name"); eleResult.appendChild(text); eleResult.appendChild(br); //br.setAttribute(name,"zhu"); }; if(typeof Array.prototype.reduce!="function"){ Array.prototype.reduce=function(callback,initialValue){ //自訂reduce函數 var previous=initialValue,k= 0,length=this.length; if(typeof initialValue==="undefined"){ //如果沒傳入初始值,則previous等於數組的第一個元素 previous=this[0]; k=1; } if(typeof callback==="function"){ for(k;k<length;k++){ this.hasOwnProperty(k)&&(previous=callback(previous,this[k],this)) } } return previous; } } var sum=[1,2,3,4].reduce(function(previous,current,array){ return previous+current; }); console.log(sum);//10 var matrix=[ [1,2],[3,4],[5,6] ]; var flattn=matrix.reduce(function(previous,current){ return previous.concat(current); }); console.log(flattn);// [1, 2, 3, 4, 5, 6]
});
註:reduce()函數,實現對數組的累加功能,需要傳遞一個callback函數和初始值initialValue,
假設callback函數它有個傳入參數,prev和next,index和array。prev和next你是必須要瞭解的。
一般來講prev是從數組中第一個元素開始的,next是第二個元素。
但是當你傳入初始值(initialValue)後,第一個prev將是initivalValue,next將是數組中的第一個元素,如果沒傳入初始值,則表示取數組的第一個元素作為初始值。
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;}var person1=new Person("zhu",23);var student1=new Student("stu1",12,1001,1);
註:Student對象繼承Person對象,只需要在Student對象裡面加一個,Person.apply(this,arguments)即可,不過只有在執行個體化時,才能看到效果。
JavaScript隨筆之——函數用法