JavaScript之函数的形参和实参

1.形参和实参的匹配问题

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <title>Document</title>
    <script type="text/javascript">
        function show(name, age) {
            console.log("My name is " + name + ", and I am " + age + " years old");
        }

        show("ysy", 20);

        //在js中, 实参的个数可以和形参个数不相等
        show("ysy");
        show();
        show("ysy", 20, "man");
    </script>
</head>

<body>

</body>

</html>

JavaScript之函数的形参和实参_第1张图片

2.JavaScript中没有重载的概念
同名函数会覆盖前面定义的函数

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <title>Document</title>
    <script type="text/javascript">
        function calc(num1, num2, num3) {
            console.log(num1 * num2 * num3);
        }

        function calc(num1, num2) {
            console.log(num1 * num2);
        }

        calc(1, 2, 3);
        calc(3, 4);
    </script>
</head>

<body>

</body>

</html>

JavaScript之函数的形参和实参_第2张图片

3.对函数的参数进行处理

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <title>Document</title>
    <script type="text/javascript">
        function calcSum(num1, num2) {
            //如果参数为undefined、null、""、NaN、0时,则默认设置为0
            /*if(!num1){
            	num1=0;
            }
            if(!num2){
            	num2=0;
            }*/
            num1 = num1 || 0;
            num2 = num2 || 0;
            //如果参数为非空字符串,则提示用户进行拼接,并输出结果
            if (isNaN(num1) || isNaN(num2)) {
                console.log("进行拼接操作:");
            }

            var sum = num1 + num2;
            console.log(sum);
        }

        calcSum(3, 6);
        calcSum(5);
        calcSum(5, null);
        calcSum(5, "");
        calcSum(5, NaN);
        calcSum(5, "hello");
    </script>
</head>

<body>

</body>

</html>

JavaScript之函数的形参和实参_第3张图片

4.如果变量名和函数名相同,则函数不生效,会被覆盖

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <title>Document</title>
    <script type="text/javascript">
        function test() {
            return 66;
        }
        var test = 12;

        console.log(test);
    </script>
</head>

<body>

</body>

</html>

JavaScript之函数的形参和实参_第4张图片

你可能感兴趣的:(JavaScript,前端,函数用法)