JavaScript隨筆之——函數用法

來源:互聯網
上載者:User

標籤:

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隨筆之——函數用法

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.