ES6 - rest 參數(shù) 與 arguments 對象

rest 參數(shù)與 arguments 對象的區(qū)別:
1)rest 參數(shù)只包含那些沒有對應(yīng)形參的實(shí)參,而 arguments 對象包含了傳給函數(shù)的所有實(shí)參。
2)arguments對象不是一個(gè)真正的數(shù)組,而 rest 參數(shù)是真正的 Array 實(shí)例,也就是說你能夠在它上面直接使用所有的數(shù)組方法,比如 sort、map、forEach、pop
3)arguments對象還有一些附加的屬性 (如callee屬性)

arguments 對象

arguments 對象是所有非箭頭函數(shù)中的函數(shù)內(nèi)部變量(arguments 對象并不是在 ES6 中提出的)

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
</style>
</style>
</head>
<body>
    <script>
        function fn() {
            console.log(arguments);

            for (var i=0; i<arguments.length; i++) {
                console.log(arguments[i]);
            }
        }
        
        // Arguments(5) [1, 3, 5, 7, 9, callee: ?, Symbol(Symbol.iterator): ?]
        // 1
        // 3
        // 5
        // 7
        // 9
        fn(1,3,5,7,9);
    </script>
</body>
</html>

rest 參數(shù)

rest 參數(shù)又叫剩余參數(shù)。它允許我們將一個(gè)或多個(gè)不定數(shù)量的實(shí)參表示為一個(gè)數(shù)組。

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
</style>
</style>
</head>
<body>
    <script>
        function fn(...args) {
            console.log(args);
        }
        
        // (5) [1, 3, 5, 7, 9]
        fn(1,3,5,7,9);

        function f(a, b, ...args) {
            console.log(args);
        }
        
        // (3) [5, 7, 9]
        f(1,3,5,7,9);

        // []
        f(1,3);
    </script>
</body>
</html>
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

友情鏈接更多精彩內(nèi)容