简体   繁体   中英

how to write a function if I don't know number of parametrs (JS, Node.js)

I want to write a function which returns me formatted string. I wrote a random function "pickRandom" do I get always one random string from the array.

My example data:

const arr = ['Hi %s', '%s nice to seee you'];

For this example is easy to write a function:

const randomOutput = (arrayToChange, variable) => {
  const randomString = pickRandom(arrayToChange);

  return util.format(randomString, variable);
};

but how to modify my function that it works with multiple and no parametrs too. Is it possible? One function for every case?

I would like that it works:

const arr = ['Hi %s', '%s nice to seee you'];
const arr = ['Hi', 'Hi you'];
const moreP= ['Hi %s, you are %d years old', '%s, your age %d'];

So in that case it wont work:

randomOutput(moreP, "Anna", 19);

You could use arguments spread syntax

const randomOutput = (arrayToChange, ...variables) => {
  const randomString = pickRandom(arrayToChange);

  return util.format(randomString, ...variables);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM