JS 3 ways to set default values for function parameters

Source: Internet
Author: User

JS default is not support funtion f($a=a){} this way of writing, if you want to set the default value of function parameters, you can refer to the following three ways:

    • The first method:

With arguments, all parameters of the function are stored in the arguments array, so we can get the corresponding parameters and assign the values.

  

function example (A, B   ) {var a = Arguments[0]? Arguments[0]: 1;  var b = arguments[1]? Arguments[1]: 2;     return a + b;}    

    • The second method of

Using the operator | |, this equivalent if(a){a=xx} notation

function Example (name,age) {   name=name| | ' Jason ';   Age =age| | ;   Alert (' Hello! I am ' +name+ ', this year ' +age+ ' years old. ‘
    • The third method of

Use jquery extensions for more parameter scenarios

functionExample (setting) {vardefaultsetting={name:' Jason ', Age:' 30 ', Sex:Male, Phone:' 100866 ', QQ:' 100866 ', Birthday:' 1949.10.01 '  };   $.extend (defaultsetting,settings); varMessage= ' Name: ' +Defaultsetting.name+ ', sex: ' +Defaultsetting.sex+ ', Age: ' +Defaultsetting.age+ ', Phone: ' +Defaultsetting.phone+ ', QQ: ' +DEFAULTSETTING.QQ+ ', Birthday: ' +Defaultsetting.birthday+ '. ‘; alert (message); }
Geugang Link: https://www.jianshu.com/p/0e6b7e7cef8c Source: Jane Book copyright belongs to the author. Commercial reprint please contact the author for authorization, non-commercial reprint please specify the source. 

JS 3 ways to set default values for function parameters

Related Article

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.