Home  >  Article  >  Web Front-end  >  js中函数function内部属性arguments详解

js中函数function内部属性arguments详解

WBOY
WBOYOriginal
2016-06-01 09:55:021931browse

在函数对象中,有一个属性arguments,通过这个属性可以获取相应的参数值。这个属性类似与一个数组,但它并不是数组,里面存储了传递进来的参数值。
看下面实例:

<code><script type="text/javascript">
function sumFun(sum1,sum2,sum3,sum4){
    alert(arguments.length);//获取实参的个数;
    for(var i=0;i<arguments.length;i++){
        alert(arguments[i]);//获取实参的每个值
    }
}
sumFun(12,26,87); //执行结果:3, 12, 26, 87;
sumFun(1,26); //执行结果:2, 1, 26;
</script></code>

在js中,函数是没有重载的,因此,我们可以利用arguments实现js中函数的重载:
实例如下:

<code><script type="text/javascript">
function doAdd() {
    if(arguments.length == 1) {
        alert(arguments[0] + 5);
    } else if(arguments.length == 2) {
        alert(arguments[0] + arguments[1]);
    }
}
doAdd(10);    //输出 "15"
doAdd(40, 20);    //输出 "60"
</script></code>

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn