1. 程式人生 > 其它 >JS 獲取函式的形參和實參的長度

JS 獲取函式的形參和實參的長度

技術標籤:JSjavascript

1. 獲取函式形參和實參的長度

function test(a, b){
    console.log(test.length);       // 形參長度
    console.log(arguments.length);  // 實參長度
}
test(1, 2, 3);

結果
在這裡插入圖片描述

2. 獲得函式的實參(物件)

function test(a, b){
    console.log(arguments);
}
test(1, 2, 3);

結果
在這裡插入圖片描述
注意:函式的實參和形參可以不想等

function test(a, b, c){
   console.
log(a, b, c); } test(1, 2); function test1(a, b){ console.log(a, b); } test1(1, 2, 3);

結果
在這裡插入圖片描述

例子:未知實參長度,求實參的和

function sum(){
    var a = 0;
    for(key in arguments){
        a += arguments[key];
    }
    console.log(a);
}
sum(1, 2, 3, 4, 5);

結果
在這裡插入圖片描述
其他的函式形參實參相關,請看下面文章的34-39
點選進入文章