重學(xué)ES系列之函數(shù)優(yōu)化

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>函數(shù)</title>
</head>
<body>
    
</body>
<script>
    function fun1(x,y) {
        return x+y
    }
    let a = fun1(1,2);
    console.log(a);//3
    // 函數(shù)參數(shù)默認(rèn)值
    function fun2(x=1,y=0) {
        return x+y
    }
    let b = fun2();
    console.log(b);//1
    // 函數(shù)多參數(shù)
    function fun3(...n) {
        console.log(n.length);
    }
    fun3(1,2,3);//3
    // 箭頭函數(shù)
    let fun4 = (v,y) =>{
        console.log(v,y);
    }
    fun4('hello','world');// hello
    let fun5=(x) => x+1 // 或這樣寫。let fun5 = x =>x+1
    console.log(fun5(1));//2
    // 函數(shù)尾調(diào)用
    // 尾調(diào)用,共用一個內(nèi)存空間。一定要注意一點(diǎn),尾調(diào)用的函數(shù)一定是最后一步(區(qū)分最后一行),切不參與運(yùn)算。
    let fun6 = (x)=>x+5;
    let fun7 =()=>{
        return fun6(2)
    }
    console.log(fun7());//7
    // 不屬于尾調(diào)用
    let fun8 = (x)=>x+2;
    let fun9 = ()=>{
        let a = fun8(2);
        return a
    }
    console.log(fun9());// 4. 雖然也可以輸出4,但是不屬于尾調(diào)用。
    // 不屬于尾調(diào)用
    let fun10 = () =>{
        return fun8(9)+1
    }
    console.log(fun10());//12 . 參與運(yùn)算了。這是不可以的,參與尾調(diào)用的必須是獨(dú)立的。不能有什么牽連。
    // 尾調(diào)用優(yōu)化
    // 遞歸
    let factorial = (n)=>{
        if(n <=1 ){
            return 1
        } else{
            return n*factorial(n-1)
        }
    }
    console.log(factorial(3)); //1*2*3
    // 優(yōu)化
    let factorial1 = (n,p=1)=>{
        if(n <= 1){
            return 1
        }else{
            let result = n*p;
            return n*factorial1(n-1,result)
        }
    }
    console.log(factorial1(3));//3*2*1

</script>
</html>

作者:Vam的金豆之路

主要領(lǐng)域:前端開發(fā)

我的微信:maomin9761

微信公眾號:前端歷劫之路