Example of setting default parameter values in Javascript
- 2020-03-30 03:55:39
- OfStack
The first:
function test(a,b){
var a = arguments[0] ? arguments[0] : 1;//Set the default value of parameter a to 1
var b = arguments[1] ? arguments[1] : 9;//Set the default value of parameter b to 9
return a+b;
The equivalent to
function test(){
var a = arguments[0] ? arguments[0] : 1;//Set the default value of parameter a to 1
var b = arguments[1] ? arguments[1] : 9;//Set the default value of parameter b to 9
return a+b;
}
Invoke the sample
alert(test()); //The output of 10
alert(test(5)); //The output of 14
alert(test(5,6)); //The output of 11
alert(test(null,6)); //The output of 7
alert(test(6,null)); //The output of 15
The second:
function test(blog,address){
blog=blog||' forget ~ Shallow, ';
address=address||'www.jb51.net';
alert(' Blog is '+blog+' The address is '+address);
}
The equivalent to
function test(blog,address){
if(!blog){blog=' forget ~ Shallow, ';}
if(!address){address='www.jb51.net';}
alert(' Blog is '+blog+' The address is '+address);
}
Invoke the sample
test(); //The blog name is forgotten ~ the address is www.jb51.net
test('csdn','blog.csdn.net'); //The blog name is CSDN and the address is blog.csdn.net
test('','blog.csdn.net/u011043843'); // Blog name is forgotten ~ Shallow,
The third:
function test(setting){
var defaultSetting={
name:' programmer ',
age:'1',
phone:'15602277510',
QQ:'259280570',
message:' You are welcome to join us '
};
$.extend(defaultSetting,setting);
var msg=' Name: '+defaultSetting.name
+' Age: '+defaultSetting.age
+' , telephone: '+defaultSetting.phone
+' . QQ Group: '+defaultSetting.QQ
+' , note: '+defaultSetting.message
+' . ';
alert(msg);
}
Invoke the sample
test(); //Output: name: program lover, age: 1, phone: 15602277510, QQ group: 259280570, description: welcome to join.
test({
name:'dwqs',
age:'20',
QQ:'461147874',
message:' Blog: www.jb51.net'
});
//Output: name: DWQS, age: 20, phone: 15602277510, QQ group: 461147874, description: blog: www.jb51.net.
Ps: this method can be used if the function has many parameters. This is an extension of JQuery, so you need to introduce JQuery.