如果我不知道参数的数量,如何编写函数(JS,Node.js)



我想写一个函数,返回格式化的字符串。我写了一个随机函数"pickRandom",我总是从数组中得到一个随机字符串。

我的示例数据:

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

对于这个例子,很容易编写一个函数:

const randomOutput = (arrayToChange, variable) => {
const randomString = pickRandom(arrayToChange);
return util.format(randomString, variable);
};

但如何修改我的函数,使其与多个参数一起工作,也没有参数。有可能吗?每个案例都有一个功能?

我希望它能起作用:

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

因此,在这种情况下,它不会起作用:

randomOutput(moreP, "Anna", 19);

您可以使用参数扩展语法

const randomOutput = (arrayToChange, ...variables) => {
const randomString = pickRandom(arrayToChange);
return util.format(randomString, ...variables);
}

最新更新