方法一:
function example(a,b){ var a = arguments[0] ? arguments[0] : 1;//设置参数a默认为1 var b = arguments[1] ? arguments[1] : 2;//设置参数b默认为2 return a+b; }
等价于:
function example(){ var a = arguments[0] ? arguments[0] : 1;//设置第一个参数的默认值为1 var b = arguments[1] ? arguments[1] : 2;//设置第二个参数的默认值为2 return a+b; }
调用,结果如下:
example(); //3 example(5); //7 example(5,10); //15 example(null,10); //10
方法二:
function example(name,age){ name=name||'陌轩'; age=age||17; console.log('My name is '+name+',I am '+age+' years old.'); }
等价于:
function example(name,age){ if(!name){name='陌轩';} if(!age){age=17;} console.log('My name is '+name+',I am '+age+' years old.'); }
调用,结果如下:
example('思梦');//My name is 思梦,I am 17 years old. example('思梦',18);//My name is 思梦,I am 18 years old. example(null,22);//My name is 陌轩,I am 22 years old.
方法三:
function example(setting){ var defaultSetting={ name:'思梦', age:'18', sex:'女', phone:'10086', QQ:'1008611', birthday:'2000.09.27' }; $.extend(defaultSetting,settings); var message='姓名:'+defaultSetting.name +',性别:'+defaultSetting.sex +',年龄:'+defaultSetting.age +',电话:'+defaultSetting.phone +',QQ:'+defaultSetting.QQ +',生日:'+defaultSetting.birthday +'。'; console.log(message); }
调用,结果如下:
example({ name:'陌轩', sex:'男', phone:'10088' }); //输出:姓名:陌轩,性别:男,年龄:18,电话:10088,QQ:1008611,生日:2000.09.27。