最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

Javascript: Only using specific parameter in function - Stack Overflow

programmeradmin4浏览0评论

I think it is rather a beginner's question: How can I address a specific parameter in a function and ignore the others?

Example:

/

function test(para_1, para_2, para_3) {
   if (para_3 == true) {
    alert('only the third parameter was successfully set!');
   }
}

test(para_3=true);

I want to individually decide whether or not I use a certain parameter in a function or not.

I think it is rather a beginner's question: How can I address a specific parameter in a function and ignore the others?

Example:

http://jsfiddle/8QuWj/

function test(para_1, para_2, para_3) {
   if (para_3 == true) {
    alert('only the third parameter was successfully set!');
   }
}

test(para_3=true);

I want to individually decide whether or not I use a certain parameter in a function or not.

Share Improve this question edited Jan 15, 2015 at 22:27 fejese 4,6284 gold badges31 silver badges37 bronze badges asked Jul 6, 2014 at 12:56 Kent MillerKent Miller 5092 gold badges8 silver badges21 bronze badges 1
  • Pass a hash map to the function – John Dvorak Commented Jul 6, 2014 at 13:02
Add a ment  | 

3 Answers 3

Reset to default 3

You can check each parameter separately using an if(param), like:

function test(para_1, para_2, para_3) {
    if (para_1) {
        // First parameter set
    }
    if (para_2) {
        // Second parameter set
    }
    if (para_3) {
        // Third parameter set
    }
}

Generally speaking, you cannot set only one parameter and expect it to be the third, because it will automatically set it to the first one, and the remaining 2 as undefined. So if you would like to call your function and only have the third set, most probably you'd do a

test(null, null, 'this_is_set');

It is not possible in JavaScript to pass named arguments. The best you can do is to accept an object as a single parameter, and from there, you decide which properties to set.

function test(obj) {
   if (obj.para_3 == true) {
    alert('only the third parameter was successfully set!');
   }
}

test({para_3:true});

You can also apply Arguments stored in an array. The entrys of the argument array will be mapped to the paramters of the function.

var arg = [];
arg[2] = true;
test.apply(this, arg);

the other way is to just set the other params to undefined:

test(undefined, undefined, true);

http://jsfiddle/8QuWj/2/

发布评论

评论列表(0)

  1. 暂无评论