1

I recently started learning Node.js and I want to know how to let a function accept multiple strings in the form of an array. For example,

export default (config: Config) => {
  return {
    target: 'https://google.com',
    endpoint: null,
    tick: 500,
    verbose: true,
    once: false,
    }
}

So instead of target: "https://google.com", I'd like something like target: ['https://google.com', 'https://facebook.com']. There's probably something I'm missing but I'm a bit lost on how to do this.

1 Answer 1

1

You can use rest parameters. The syntax is

 const hello = (...args) => {
     // args is now an array
     console.log(args)
 }

Then you can use it like so:

hello('This ', 'is ', 'an ', 'example') // outputs ['This ', 'is ', 'an ', 'example']

You can pass any number of arguments in it.

So back to your example, you could have some like

const example = (...targets) => {
  return {
    target: targets,
    endpoint: null,
    tick: 500,
    verbose: true,
    once: false,
  }
}

module.exports = example

And you can use it like so

const example = require('./example')

let val = example('google', 'twitter', 'yahoo')
console.log(val)

Rest parameter should be the last parameter in your function. So if you want to pass some other params, the syntax is

function hello(param, ...rest) {
    // rest is an array
    ...
}

You could also directly pass an array or a variable referencing an array:

function hello(param) {
    ...
    console.log(param)
}

hello(["hello", "world"]) // outputs ["hello", "world"]
or
var arr = ["hello", "world"]
hello(arr)

You can also read more about the Array-like object arguments here

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.