Home  >  Article  >  Web Front-end  >  An alternative implementation method for setting default values ​​for js function parameters_javascript skills

An alternative implementation method for setting default values ​​for js function parameters_javascript skills

WBOY
WBOYOriginal
2016-05-16 16:46:571224browse

A very convenient usage of php is to directly set default values ​​for parameters when defining functions, such as:

Copy code The code is as follows :

function simue ($a=1,$b=2){
return $a $b;
}
echo simue(); //Output 3
echo simue(10); //Output 12
echo simue(10,20); //Output 30

But js cannot be defined this way. If you write function simue(a= 1,b=2){} will prompt that there is a missing object.

There is an array arguments for storing parameters in the js function. All parameters obtained by the function will be saved into this array one by one by the compiler. Therefore, our js version of the function that supports parameter default values ​​can be implemented through another alternative method. Modify the above example:
Copy code The code is as follows:

function simue (){
var a = arguments[0] ? arguments[0] : 1;
var b = arguments[1] ? arguments[1 ] : 2;
return a b;
}
alert( simue() ); //Output 3
alert( simue(10) ); //Output 12
alert( simue( 10,20) ); //Output 30
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