(go) JS function parameter Set default value

Source: Internet
Author: User

PHP has a handy use when defining a function to set a default value directly to the parameter, such as:

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 can not be so defined, if you writefunction Simue (a=1,b=2) {} will prompt for missing objects.

There is an array of stored parameters in the JS functionarguments , the parameters obtained by all functions are saved to the array by the compiler. So our JS version of the support parameter default value of the function can be implemented in another way, modify the above example:

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.