Home  >  Article  >  Web Front-end  >  Example of setting default parameter values ​​in Javascript_javascript skills

Example of setting default parameter values ​​in Javascript_javascript skills

WBOY
WBOYOriginal
2016-05-16 16:36:261187browse

First type:

function test(a,b){

var a = arguments[0] ? arguments[0] : 1;//设置参数a的默认值为1

var b = arguments[1] ? arguments[1] : 9;//设置参数b的默认值为9

return a+b;

The equivalent is

function test(){

var a = arguments[0] ? arguments[0] : 1;//设置参数a的默认值为1

var b = arguments[1] ? arguments[1] : 9;//设置参数b的默认值为9

return a+b;

}

Call example

alert(test()); //输出10

alert(test(5)); //输出14

alert(test(5,6)); //输出11

alert(test(null,6)); //输出7

alert(test(6,null)); //输出15

Second type:

function test(blog,address){

blog=blog||'淡忘~浅思';

address=address||'www.jb51.net';

alert('博客名是'+blog+'的地址是'+address);

}

The equivalent is

function test(blog,address){

if(!blog){blog='淡忘~浅思';}

if(!address){address='www.jb51.net';}

alert('博客名是'+blog+'的地址是'+address);

}

Call example

test(); //博客名是淡忘~浅思的地址是www.jb51.net

test('csdn','blog.csdn.net'); //博客名是csdn的地址是blog.csdn.net

test('','blog.csdn.net/u011043843'); //博客名是淡忘~浅思

Third type:

function test(setting){

var defaultSetting={

name:'程序爱好者',

age:'1',

phone:'15602277510',

QQ:'259280570',

message:'欢迎你的加入'

};

$.extend(defaultSetting,setting);

var msg='姓名:'+defaultSetting.name

+',年龄:'+defaultSetting.age

+',电话:'+defaultSetting.phone

+',QQ群:'+defaultSetting.QQ

+',说明:'+defaultSetting.message

+'。';
alert(msg);
}

Call example

test(); //输出:姓名:程序爱好者,年龄:1,电话:15602277510,QQ群:259280570,说明:欢迎你的加入。

test({

name:'dwqs',

age:'20',

QQ:'461147874',

message:'博客:www.jb51.net'

});

//输出:姓名:dwqs,年龄:20,电话:15602277510,QQ群:461147874,说明:博客:www.jb51.net。

ps: This method can be used when there are many function parameters. This is an extension of JQuery, so JQuery needs to be introduced.

Statement:
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