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);