美文网首页前端基础学习
函数05(形参、实参、默认参数)

函数05(形参、实参、默认参数)

作者: 小雪洁 | 来源:发表于2020-04-26 21:55 被阅读0次
    <!DOCTYPE html>
    <html>
        <head>
            <meta charset="utf-8">
            <title>形参和实参</title>
        </head>
        <body>
        </body>
        <script>
            function sum(a,b){
                return a+b;
            }
            //实参个数可以比形参个数多,反之不行;
            console.log(sum());//NaN
            console.log(sum(1));//NaN
            console.log(sum(1,2,3,6));//3
        </script>
    </html>
    
    <html>
        <head>
            <meta charset="utf-8">
            <title>默认参数</title>
        </head>
        <body>
        </body>
        <script>
            //旧版js中默认参数赋值
            function avg(total,year){
                year=year||1;
                return Math.round(total/year);
            }
            console.log(avg(3000,3));//1000
            console.log(avg(3000));//3000
            //新版js
            function average(total,year=1){
                return Math.round(total/year);
            }
            console.log(average(3000));//3000
            console.log(average(3000,3));
            //数组排序
            function sortArray(array,type="asc"){
                return array.sort(function(a,b){
                    return type=="asc"?a-b:b-a;
                });
            }
            console.log(sortArray([3,2,1,4,5]));// [1, 2, 3, 4, 5]
            //折扣函数,注意默认参数放在后面,函数调用时会按顺序赋予形参值
            function sum(total,discount=1,dis=1){
                return total*discount*dis;
            }
            console.log(sum(2000,0.9));
        </script>
    </html>
    
    

    相关文章

      网友评论

        本文标题:函数05(形参、实参、默认参数)

        本文链接:https://www.haomeiwen.com/subject/vfjswhtx.html