Passing the argument name while calling function in javascript - Stack Overflow

I have a function which looks like this:function helo(a,b){if(a){do something}if(b){do something}}

I have a function which looks like this:

function helo(a,b){
    if(a)
    {
       //do something
    }
    if(b)
    {
       //do something
    }
}

Now if I want to specify which parameter has to be passed while calling helo, how do I do it in javascript, i.e

If I want to send only parameter b, how do I call the function helo?

helo(parameterB); 

Right now parameter a takes the value

I have a function which looks like this:

function helo(a,b){
    if(a)
    {
       //do something
    }
    if(b)
    {
       //do something
    }
}

Now if I want to specify which parameter has to be passed while calling helo, how do I do it in javascript, i.e

If I want to send only parameter b, how do I call the function helo?

helo(parameterB); 

Right now parameter a takes the value

Share Improve this question asked Jul 2, 2015 at 14:32 user1692342user1692342 5,24713 gold badges79 silver badges138 bronze badges 1
  • That should work. However what I am looking for is if there is a way to specify the exact parameter – user1692342 Commented Jul 2, 2015 at 14:35
Add a ment  | 

4 Answers 4

Reset to default 9

Your best bet would be to just pass an object containing all parameters:

function myFunction(parameters){
    if(parameters.a) {
        //do something
    }
    if(parameters.b) {
        //do something
    }
}

Then you can call the function like this:

myFunction({b: someValue}); // Nah, I don't want to pass `a`, only `b`.

In case you want to be able to pass falsy values as parameters, you're going have to change the ifs a bit:

if(parameters && parameters.hasOwnProperty('a')){
    //do something
}

Another option would be to simply pass null (or any other falsy value) for parameters you don't want to use:

helo(null, parameterB); 

In JavaScript parameters is matched according to order, so if you want to pass only second parameter, you must leave first one empty

helo(null,parameterB); 

Instead of passing multiple distinct arguments, you can pass in a single argument, which is an object.

For Example:

function helo(args){
    if(args.a){ ... }
    if(args.b){ ... }
}

helo({b: 'value'});

You can use either of the below two syntax:

helo(null,parameterB); 

or

helo(undefined,parameterB); 

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745525376a4631445.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信