Home > Web Front-end > JS Tutorial > body text

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

WBOY
Release: 2016-06-01 09:55:02
Original
1930 people have browsed it

在函数对象中,有一个属性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>
Copy after login

在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>
Copy after login

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!