JavaScript-函数 arguments

因为 console.log(); 也是通过 () 来调用的, 所以 log 也是一个函数。

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Demo</title>
    <script type="text/javascript">
        console.log();
        
        function say() {
            console.log("hello world");
        }

        window.say();
    </script>
</head>
<body>
</body>
</html>

log 函数的特点,可以接收 1 个或 多个 参数。

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Demo</title>
    <script type="text/javascript">
        console.log(1);
        console.log(1, 2);
        console.log(1, 2, 3);
    </script>
</head>
<body>
</body>
</html>

为什么 log 函数可以接收 1 个或多个参数呢?内部的实现原理就用到了 arguments

arguments 的作用

保存所有传递给函数的实参。🐤注意点:每个函数中都有一个叫做 arguments 的东东,arguments 其实是一个伪数组。

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Demo</title>
    <script type="text/javascript">
        function getSum() {
            console.log(arguments);
            console.log(arguments[0]);
            console.log(arguments[1]);
            console.log(arguments[2]);

            let sum = 0;
            for (let i = 0; i < arguments.length; i++) {
                let num = arguments[i];
                sum += num;
            }
            return sum;
        }

        let res = getSum(10, 20, 30, 40);
        console.log(res);
    </script>
</head>
<body>
</body>
</html>

posted @ 2021-07-01 16:28  BNTang  阅读(61)  评论(0编辑  收藏  举报