js中arguments的使用
在JavaScript中,arguments对象是比较特别的一个对象,实际上是当前函数的一个内置属性。arguments非常类似Array,但实际上又不是一个Array实例。其实Javascript并没有重载函数的功能,但是Arguments对象能够模拟重载。Javascrip中每个函数都会有一个Arguments对象实例arguments,它引用着函数的实参,可以用数组下标的方式"[]"引用arguments的元素。arguments.length为函数实参个数,arguments.callee引用函数自身。
可以通过下面的例子来看一下arguments的具体使用方法
function test(){ if(arguments.length>0){ for(p of arguments){ console.log(p); } } } test("a","sdf","段落"); //输出结果为 a sdf 段落
arguments.callee引用函数自身的意思看下面代码即可理解
function test(){ if(arguments.length>0){ console.log(arguments.callee) } } test("a","sdf","段落"); /* 方法调用之后的输出结果为 function test(){function test(){ if(arguments.length>0){ console.log(arguments.callee); } } */
通过上面的例子可以看到callee的作用,当需要使用递归来处理问题时callee就派上了用场
function count(a){ if(a==1){ return 1; } return a + arguments.callee(--a);//此处的调用亦可使用cont(--a)的方式 } var mm = count(10); console.log(mm);//输出结果为55