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
3 Answers
Reset to default 3You 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/