arguments对象不能显式创建,arguments对象只有函数开始时才可用。函数的arguments对象并不是一个数组,访问单个参数的方式与访问数组元素的方式相同。索引 n 实际上是 arguments 对象的 0…n 属性的其中一个参数。
先看一个例子:
function test(a,b,c,d){
return a + b;
}
alert(test(10,20));
输出结果:30
javascript的形参和实参个数可以不同。如果不传参也不会报错alert(test()); 运行后弹出:NaN
function test(a,b,c,d){
alert(test.length);
}
test();
输出:4
(a b c d)
function test(a,b,c,d){
alert(arguments.length);
// alert(test.length);
}
test(10,20);
输出:2 传入的(10,20)
function test(a,b,c,d){
alert(arguments[0]);
alert(arguments[1]);
// alert(arguments.length);
}
test(10,20);
弹出: 10、20
当传入的参数和函数形参不同的时候,我们可以进行判断:
function test(a, b, c, d) {
if (test.length == arguments.length) {
return a + b;
} else {
return '参数不正确!';
}
}
test(10, 20);
输出:参数不正确
不建议使用上面判断的方法,因为直接使用函数名会带来不可预料的问题,比如我们把test=null了以后就会执行异常
建议使用下面的方法:arguments.callee
function test(a, b, c, d) {
if (arguments.callee.length == arguments.length) {
return a + b;
} else {
return '参数不正确!';
}
}
alert(test(10, 20));
arguments 对象 可以访问函数的实际参数,arguments 对象 只能在函数的内部访问和使用,arguments对象 用的最多的 还是做递归操作 ,arguments.callee 对自己本身引用进行递归
function fact(num){
if(num <=1) return 1 ;
else return num*arguments.callee(num-1);
}
var F = fact ;
fact = null;
alert(F(5));
fact=null后依然可以输出:120
我们把arguments.callee换成fact
function fact(num) {
if (num <= 1)
return 1;
else
return num * fact(num - 1);
}
//alert(fact(5));
var F = fact;
fact = null;
alert(F(5));
出错:Uncaught TypeError: object is not a function