好程式設計師web前端教程分享前端javascript練習題之閉包案例

好程式設計師IT發表於2019-11-28

  好程式設計師web 前端教程分享 前端javascript 練習題閉包案例編寫一個求和函式sum,使輸入sum(2)(3)或輸入sum(2,3),輸出結果相同

可以傳入多個引數

function sum(){    

    var num = arguments[0];    

    if(arguments.length==1){       

    return function(sec){           

        return num+sec;       

            }    

        }else{        

        var num = 0;        

        for(var i = 0;i<arguments.length;i++){           

            num = num + arguments[i];        

            }   

            return num;    

        }

    }

遞迴----深複製

function deepCopy(obj){

                if(Array.isArray(obj)){

                    var newobj=[];

                }else{

                    var newobj={};

                }

                

                for(var i in obj){

                    if(typeof obj[i]=="object"){

                     newobj[i]=deepCopy(obj[i]);

                        

                    }else{

                        newobj[i]=obj[i];

                    }

                }

                return newobj;

            }

 

定時器案例

迴圈列印5,6,7,8,9,10,9,8,7,6,5,6,7…迴圈輸出

var a=4;

        var b=1;

        setInterval(function(){

            a=a+b;

            if(a==10){

                b=-1;

            }else if(a==5){

                b=1;

            }

            console.log(a);

        },500);

 


來自 “ ITPUB部落格 ” ,連結:http://blog.itpub.net/69913892/viewspace-2666111/,如需轉載,請註明出處,否則將追究法律責任。

相關文章