Home > Web Front-end > JS Tutorial > body text

JS function multiple parameter default value specification method analysis

高洛峰
Release: 2016-12-03 16:12:55
Original
1468 people have browsed it

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){ … }
Copy after login

When you need to set a default value for p1

function mfun(p1){
if(p1===undefined) p1=5; //默认值设为5
…
}
Copy after login

When a function requires 2 parameters, I used to write like this

function mfun(p1,p2){…}
Copy after login

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'
…
}
Copy after login

The following are some error examples:

Requires 2 parameters. When the second parameter is optional, define

function mFun(p1){...}
function mFun(p1,p2){...}
Copy after login

* 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'){...}
Copy after login

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
Copy after login


Related labels:
js
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template