[js]js中函数传参判断

时间:2023-03-08 16:19:07
[js]js中函数传参判断

1,通过||

        function fun(x,y){
x=x||0;
y=y||1;
alert(x+y);
}
fun();

2.通过undefined对比

       function fun(x,y){
if(x==undefined){
x=100;
}
y=y==undefined?200:y;
alert(x+y);
}
fun();

3.通过argument

		function fun(x,y){
x=arguments[0]?arguments[0]:100;
y=arguments[1]?arguments[1]:200;
return x+y;
}
alert(fun());
alert(fun(1,2));

4,形参 实参 解释argument

    function fn(a,b)
{
console.log(fn.length); //得到是 函数的形参的个数
//console.log(arguments);
console.log(arguments.length); // 得到的是实参的个数
if(fn.length == arguments.length)
{
console.log(a+b);
}
else
{
console.error("对不起,您的参数不匹配,正确的参数个数为:" + fn.length);
}
//console.log(a+b);
}
fn(1,2);
fn(1,2,3);