Reputation: 2098
I have a JavaScript function which currently accepts one argument:
foo(country) { ... }
and so is used like foo('US')
I need to extend this function to accept one or multiple countries:
foo('US')
foo('US', 'CA', 'UK')
foo(['US', 'CA', 'UK'])
Is any syntax/keyword feature for this? In C# we have a params
keyword for this
Upvotes: 2
Views: 1123
Reputation: 21926
Use a gather:
function(...args) {
// do something with args
}
This is generally considered preferable to using arguments
because arguments is a weird case: it isn't truly an array, hence the awkward old idiom you'll still sometimes see:
var args = Array.prototype.slice.call(arguments);
Upvotes: 5
Reputation: 386560
You could take rest parameters ...
and flat the array.
function foo(...args) {
return args.flat();
}
console.log(foo('US'));
console.log(foo('US', 'CA', 'UK'));
console.log(foo(['US', 'CA', 'UK']));
Upvotes: 3
Reputation: 10193
arguments
in function plays the same role as params
in c#.
function foo() {
console.log(arguments);
}
foo('a','b','c');
foo('a');
Upvotes: 1
Reputation: 2197
Yes. arguments
.
foo(country){
console.log(arguments)
}
It looks like an array. It's actually an object with numbered keys, but you can still loop through it and get the information you need.
Upvotes: 1