How to set the default parameters of JavaScript Functions

Source: Internet
Author: User
  1. We can define a function similar to this in PHP or C/C ++:
  2. Function func (INT num = 1 ){...}
  3. If there is no parameter when you call func, the default value is 1, which cannot be directly written in Javascript. to implement similar functions, you can use the arguments object of javascript:
  4. PHP programmer site
  5. This object represents the function being executed and the parameters of the function that calls it.
  6. The usage is as follows: PhP programmer's house
  7. [Function.] arguments [N]
  8. PHP programmer site
  9. Function
  10. Optional. Name of the function object currently being executed.
  11. Phperz.com
  12. N phperz.com
  13. Required. The index of the parameter value starting from 0 to be passed to the function object.
  14. The following methods can be used to meet our requirements:
  15. WWW ~ Phperz ~ Com
  16. Reference content is as follows:
  17. <Script language = JavaScript>
  18. Function writestr ()
  19. {
  20. VaR STR = arguments [0] | "I am the default parameter ";
  21. Return STR;
  22. }
  23. Document. Write (writestr () + "<br> ");
  24. Document. Write (writestr ("I am the set parameter") + "<br> ");
  25. </SCRIPT>
  26. In this example, we define only one default parameter. If you want to define two parameters, you can add one more parameter to the function.
  27. VaR str2 = arguments [0] | "I am the default parameter 2.
  28. PHP programmer's house
  29. Note: This method has a problem, that is, when the parameter is 0, false, or null, it is invalid.

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.