arguments對象簡介
arguments 是一種類數組對象,它只在函數的內部起作用,並且永遠指向當前函數的調用者傳入的所有參數,arguments類似Array,但它不是Array。
1.使用arguments來得到函數的實際參數。
arguments[0]代表第一個實參
ep:
function test(a,b,c,d) {
alert(test.length); //4
alert(arguments.length); //2
if(test.length == arguments.length) { //判斷形參與實參是否一致
return a+b;
}
}
test(1,2);
2.arguments對象的callee和caller屬性
(1).arguments.callee指向函數本身
function test(a,b) {}
arguments.callee 即爲 test 函數本身;
arguments.callee.length 即爲函數的形參個數 2
(2).arguments.callee.caller 保存着調用當前函數的函數引用(若函數在全局作用域中運行,caller則爲 null)
ep:
function add(x,y) {
console.log(arguments.callee.caller);
}
function test(x,y) {
add(x,y);
}
test(1,2); //結果爲:function test(x,y) {add(x,y);}
此時,test()在函數內部調用了ad(0函數,所以arguments.callee.caller則指向了test()函數。
3.arguments對象用的最多的,還是遞歸操作。
ep:
function fact(num) {
if(num < 1)
return 1;
else
// return num*fact(num-1); //(1)
return num*arguments.callee(num-1); //(2)
}
var F = fact;
alert(F(5)); //120
fact = null;
alert(F(5)); //若使用(1)來實現fact()遞歸,則會報錯。fact is not a Function ;若使用(2)來實現遞歸,則可以輸出120