Home >Web Front-end >JS Tutorial >JS function multiple parameter default value specification method analysis
The example in this article describes the method of specifying default values for multiple parameters of JS functions. Share it with everyone for your reference, the details are as follows: When the
function has a parameter, it used to be defined like this (the parameter is p1):
function mfun(p1){ … }
When you need to set a default value for p1
function mfun(p1){ if(p1===undefined) p1=5; //默认值设为5 … }
When a function requires 2 parameters, I used to write like this
function mfun(p1,p2){…}
Later I found that there is no need to write like this at all. The js function does not even need to preset parameter names in brackets. You can pass in as many as you want in the following way Parameters are automatically adapted. When not defined, these unassigned parameters will be undefined when called
The following example demonstrates a js function with 2 parameters
function mFun(){ var p1 = arguments[0] ? arguments[0] : -1; //设置参数p1默认值为-1 var p2 = arguments[1] ? arguments[1] : ‘ABC'; //p2默认值 ‘ABC' … }
The following are some error examples:
Requires 2 parameters. When the second parameter is optional, define
function mFun(p1){...} function mFun(p1,p2){...}
* In this way of writing, mFun(p1) will be overwritten by the following function. When only one parameter is passed in, p2 will prompt undefined
funciton mfun(p1,p2='xxx'){...}
This is a php habit.. =___=b..
Look at another example:
function simue (){ var a = arguments[0] ? arguments[0] : 1; var b = arguments[1] ? arguments[1] : 2; return a+b; } alert( simue() ); //输出3 alert( simue(10) ); //输出12 alert( simue(10,20) ); //输出30