arguments介紹(二)

1.1 將參數從一個函數傳遞到另外一個函數

下面是將參數從一個函數傳遞到另外一個函數的推薦作法。數組

function foo() {
    bar.apply(this, arguments);
}
function bar(a, b, c) {
    // logic
}

2. ES6 中的 arguments

2.1 擴展操做符

function func() {
    console.log(...arguments);
}

func(1, 2, 3);

執行結果是:app

1 2 3

2.2 Rest 參數

function func(firstArg, ...restArgs) {
    console.log(Array.isArray(restArgs));
    console.log(firstArg, restArgs);
}

func(1, 2, 3);
true
1 [2, 3]

2.3 默認參數

function func(firstArg = 0, secondArg = 1) {
    console.log(arguments[0], arguments[1]);
    console.log(firstArg, secondArg);
}

func(99);
99 undefined
99 1

可見,默認參數對 arguments 沒有影響,arguments 仍是僅僅表示調用函數時所傳入的全部參數。函數

2.4 arguments 轉數組

Array.from() 是個很是推薦的方法,其能夠將全部類數組對象轉換成數組。this

相關文章
相關標籤/搜索