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

JavaScript single argument or array - Stack Overflow

programmeradmin2浏览0评论

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

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

Share Improve this question asked Oct 2, 2020 at 15:52 Luke1988Luke1988 2,1382 gold badges31 silver badges50 bronze badges
Add a ment  | 

4 Answers 4

Reset to default 5

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);

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']));

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.

arguments in function plays the same role as params in c#.

function foo() {
  console.log(arguments);
}

foo('a','b','c');
foo('a');

发布评论

评论列表(0)

  1. 暂无评论