理解函数调用_使用argument参数

<!DOCTYPE html>
<html lang="en">
<head>  
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <script src="../unitl/test.js"></script>
    <style>
        #results li.pass {color:green;}
        #results li.fail {color:red;}
    </style>
</head>
<body>
    <ul id="results"></ul>
</body>
<script>



    //声明一个函数,具有3个形参:a,b,c
    function whatever(a,b,c) {


        //值的准确性检验
        assert(a===1,"The value of a is 1");
        assert(b===2,"The value of b is 2");
        assert(c===3,"The value of c is 3");

        //共传入5个实参。
        assert(arguments.length ===5,"We've passed in 5 parameters");



        //验证传入的签3个实参与函数的3个形参匹配
        assert(arguments[0]===a,"The first arguments is assigned to a");
        assert(arguments[1] ===b, "The second argument is assigned to b");
        assert(arguments[2]===c,"The third argument is assigned to c");

        //验证额外的参数可以通过参数arguments获取。
        assert(arguments[3]===4,"We can access the fourth argument");
        assert(arguments[4]===5 ,"We can access the fifth argument");

    }

    //调用函数时闯入5个参数
    whatever(1,2,3,4,5);
   


</script>
</html>

即时这里的whatever函数只定义了3个形参,但在调用的时候传入了5个参数;whatever(1,2,3,4,5);

      function whatever(a,b,c) {
            ...
      }

我们可以通过对应的函数参数a,b和c访问到前3个参数的值;

      assert(a===1,"The value of a is 1");
      assert(b===2,"The value of b is 2");
      assert(c===3,"The value of c is 3");

我们还可以使用arguments.length属性来获取传递给函数的实际参数的个数。
通过数组下标的方式还可以访问到arguments参数的每个参数值。值得注意的是,这个也包括没有和函数形参相关联的剩余参数。

        assert(arguments[0]===a,"The first arguments is assigned to a");
        assert(arguments[1] ===b, "The second argument is assigned to b");
        assert(arguments[2]===c,"The third argument is assigned to c");



        assert(arguments[3]===4,"We can access the fourth argument");
        assert(arguments[4]===5 ,"We can access the fifth argument");

arguments不是一个一个数组。你可能会被它的用法误导,毕竟他有length属性,而却可以通过数组下标的方式访问到每个元素。但它并非JavaScript数组,如果你尝试在arguments对象上使用数组的方法
如(sort方法),会发现最终会报错。arguments对象仅仅是一个类数组的结构,在使用中要尤为注意。

posted @ 2020-12-11 13:52  yongjar  阅读(167)  评论(0编辑  收藏  举报