A simple parameter verification class

Source: Internet
Author: User

When writing JS overload functions, we need to determine different input conditions.

However, we generally determine the number of parameters, but this is often not the case:

Function ABC (A, B, C)

A: String

B: Number

C: Boolean

Or

A: String

B: String

C: Number

In both cases, the number of parameters is 3, but the parameter type is completely different. How can we easily build an overloaded function?

 

Use my class:

Class Code (very short ):

var Param = {    varify: function (oParam, sParamType) {        var arrParam = sParamType.split(",");        if (arrParam.length == oParam.length) {            for (var nIndex = 0; nIndex < oParam.length; nIndex++) {                if (typeof oParam[nIndex] != String(arrParam[nIndex]).toLowerCase()) {                    return false;                }            }            return true;        } else {            return false;        }    }};

Application Case code:

function modify(s) {    switch (true) {        case Param.varify(arguments, "string,string,number"):            alert(arguments[0] + " " + arguments[1] + "=" + arguments[2].toString());            break;        case Param.varify(arguments, "string,string"):            alert("Fist Name:"+arguments[1] + "\nLast Name:" + arguments[0]);            break;        default:            alert("nothing");    }}modify("Michael", "Jackson");modify("Michael", "Jackson",5);modify("Michael", "Jackson","King Of Pop");

Run the sample code to experience the pleasure!

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.