前端基础学习

函数08(递归、回调函数、函数中的展开语法)

2020-04-26  本文已影响0人  小雪洁
<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <title>递归算法</title>
    </head>
    <body>
    </body>
    <script>
        //递归算法写阶乘函数
        function factorial(num){
            //return num==1?1:num*factorial(num-1);
            return num==1?1:num*factorial(--num);
        }
        console.log(factorial(5));//120
        //递归求和
        function sum(...args){
            return args.length==0?0:args.pop()+sum(...args);
        }
        console.log(sum(1,2,3,4,5));
        //递归打印星星
        /* function star(a){
            if(a==0){
                return "";
            }else{
                document.write("*".repeat(a)+"<br/>");
                star(--a);
            }
        } */
        function star(a){
            //console.log(document.write("*".repeat(a)+"<br/>"));//undefined
            return a?document.write("*".repeat(a)+"<br/>")||star(--a):"";
        }
        star(5);
    </script>
</html>
<!DOCTYPE html>
<html>
   <head>
       <meta charset="utf-8">
       <title>回调函数</title>
   </head>
   <body>
       <button>haoxuejie</button>
   </body>
   <script>
       //在函数A内调用的函数B,则函数B就称为回调函数
       document.querySelector("button").addEventListener("click",function(){
           alert(this.innerHTML);
       });//addEventListener()里面定义的匿名函数就是回调函数
       let a=[1,2,3,4,5];
       //map()里面的定义的函数就是回调函数
       a.map(function(item,index,arr){
           arr[index]+=10;
       });
       console.log(a);// [11, 12, 13, 14, 15]
       
   </script>
</html>

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <title>函数中使用展开语法</title>
    </head>
    <body>
    </body>
    <script>
        //收和放
        //展开语法的表达式在等号右边就是放
        let name=["hxj","ydc"];
        let [h,y]=[...name];//展开语法在等号右边把name数组展开赋值给左边相应变量
        console.log(h,y);
        //展开语法表达式在等号左边就是收集
        let [a,...hy]=['hhh','hxj','ydc'];
        console.log(a);//hhh
        console.log(hy);//['hxj','ydc']
        //旧版js中如果函数参数不确定有多少个,从arguments中获取参数信息
        //新版js中函数形参使用展开语法
        function sum(...args){
            //args就是一个数组,可以直接用数组方法
            //console.log(args);//[1, 1, 3, 4, 5]
            return args.reduce((a,b)=>a+b);
        }
        console.log(sum(1,1,3,4,5));
        //注意函数参数中使用展开语法,这个展开语法的表达式要放在最后,如下
        //计算折扣后的总价
        function total(discount,...price){
            let tp= price.reduce((a,b)=>a+b);
            return tp*(1-discount);
        }
        console.log(total(0.1,100,200,300));
    </script>
</html>
上一篇下一篇

猜你喜欢

热点阅读