前言
javascript中,函數不介意傳遞進來多少參數,也不在乎傳進來的參數什么數據類型,甚至不傳參數。
javascript中的函數定義未指定函數形參的類型,函數調用也不會對傳入的實參值做任何類型檢查。
同名形參
非嚴格模式下,函數中可以出現同名形參,只能訪問最后出現的該名稱的形參。在嚴格模式下,拋出語法錯誤。
1 function add(x,x,x){ 2 return x; 3 } 4 console.log(add(1,2,3)); //3
參數個數
實參數大於形參數:
1 function say(name,message){ 2 console.log("hello"+name+message); 3 } 4 say("world","!","byebye"); //helloworld!
實參數小於形參數:
1 function say(name,message){ 2 console.log("hello"+name+message); 3 } 4 say("world!"); //helloworld!undefined
注意:在js中變量定義的時候,如果未給一個變量賦初值那么該變量的類型為undefined。在函數調用時,無論參數個數如何變化函數都會執行,所有在js中函數不介意傳遞進來多少參數,也不在乎傳遞進來的參數是什么數據類型。發生函數調用時可以給一個實參也可以給多個實參,因為在js中的參數在內部用一個數組來表示。函數接收到的始終是這個數組,不關心參數個數,在函數內可以通過arguments對象來訪問這個參數數組,獲取傳遞給參數的每個參數。arguments對象和數組對象類似,可以通過下標來獲取傳入的每一個元素;也可以使用length屬性來確定傳遞進來多少個參數。
arguments對象並不是Array的實例,它是一個類數組對象,可使用方括號語法訪問它的每個元素
1 function say(name){ 2 console.log(arguments[0],arguments[1]) 3 } 4 say("hello","world"); //hello world
arguments對象的length屬性顯示實參的個數,函數的length屬性顯示形參的個數
1 function say(name){ 2 console.log(arguments.length); 3 } 4 say("hello","world"); //2 5 console.log(say.length); //1
形參只是提示便利,但不是必需的
1 function say(){ 2 return arguments[0]+arguments[1]; 3 } 4 console.log(say("hello","world!")) //helloworld!
對象參數
1 function arraycopy(from,form_start,to,to_start,length){ }
通過名/值對的形式傳入參數,這樣參數的順序無關緊要了。定義函數的時候,傳入的實參都寫入一個單獨的對象中,調用時傳入一個對象,對象中的名/值對是真正需要的實參數據
1 function easycopy(args){ 2 arraycopy(args.from,args.form_start||0,args.to,args.to_start||0,args.length) ; 3 } 4 var a = [1,2,3,4],b=[]; 5 easycopy({form:a,to:b,length:4});
同步
當形參與實參的個數相同時,arguments對象的值和對應形參的值保持同步
1 function test(num1,num2){ 2 console.log(num1,arguments[0]); //1 1 3 arguments[0] = 2; 4 console.log(num1,arguments[0]); //2 2 5 num1 = 10; 6 console.log(num1,arguments[0]); //10 10 7 } 8 test(1);
注:雖然命名參數和對應arguments對象的值相同,但並不是相同的命名空間。它們的命名空間是獨立的,但值是同步的
嚴格模式下,arguments對象的值和形參的值是獨立的
1 function test(num1,num2){ 2 "use strict"; 3 console.log(num1,arguments[0]); //1 1 4 arguments[0] = 2; 5 console.log(num1,arguments[0]); //1 2 6 num1 = 10; 7 console.log(num1,arguments[0]); //10 2 8 } 9 test(1)
當形參並沒有對應的實參時,arguments對象的值與形參的值並不對應
1 function test(num1,num2){ 2 console.log(num1,arguments[0]); //undefined,undefined 3 num1 = 10; 4 arguments[0] = 5; 5 console.log(num1,arguments[0]); //10 5 6 } 7 test()