当前位置:Gxlcms > JavaScript > arguments及arguments.callee

arguments及arguments.callee

时间:2021-07-01 10:21:17 帮助过:6人阅读

首先有一个JavaScript函数

代码

<span style="font-family: 'courier new', courier;">function test(a, b, c, d) {  
    return a + b;  
}</span>

在JavaScript中调用一个函数的实参个数可以和被调用函数的形参个数不匹配,要求并没有像java那么严格,因为在ECMAScript中的参数在内部是用一个数组来表示的,函数被调用的时候接收到的始终是这个数组,而不关心数组中包含包含哪些参数,甚至是没有元素也无所谓

Js代码

<span style="font-family: 'courier new', courier;">function test(a, b, c, d) {  
    return a + b;  
}

console.log(test(10, 20));</span>

这样的代码在JavaScript中是不会报错的,同时在JavaScript中我们可以通过下列代码获得实参及形参的个数

Js代码

<span style="font-family: 'courier new', courier;">function test(a, b, c, d) {  
    console.log(test.length);//这里获得的是形参的个数  
    console.log(arguments.length);//这里获得的是实参的个数,这段代码必须放在函数内部  
}

console.log(test(10, 20));</span>

同时还有一个类似的对象叫做arguments.calee,这个对象通常被用作递归调用

Js代码

<span style="font-family: 'courier new', courier;">function test2(num) {  
    if(num <= 1) return 1;  
    else return num*arguments.callee(num-1);  
}  
  
console.log(test2(5));</span>

如果将arguments.callee(num-1)改为test2(num-1),会在下列调用中会报错

Js代码

<span style="font-family: 'courier new', courier;">var F = test2;  
test2 = null;  
console.log(F(5));</span>

人气教程排行