如何在JavaScript函数中接受无限的参数

Let’s say we have a function called join() whose job is to join all the strings we pass to it.

假设我们有一个名为join()的函数,其作用是将传递给它的所有字符串连接起来。

For example we write a prototype that accepts 2 strings:

例如,我们编写了一个接受2个字符串的原型:

const join = (string1, string2) => {
  return string1 + string2
}

and when we call it, we get a string that is the concatenation the 2 arguments we pass:

当我们调用它时,我们得到一个字符串,该字符串是我们传递的两个参数的串联:

join('hi', ' flavio') // 'hi flavio'

One simple way is to append additional parameters that default to an empty string, like this:

一种简单的方法是将默认附加到空字符串的其他参数附加起来,如下所示:

const join = (string1, string2, string3 = '') => {
  return string1 + string2 + string3
}

but this approach does not scale well, because we’d need to add a large number of parameters and our code would look pretty bad.

但是这种方法无法很好地扩展,因为我们需要添加大量参数,并且我们的代码看起来很糟糕。

Instead, we can use this syntax, with the spread operator (...) followed by the name of the parameter we want to use. Inside the function, the parameter is an array, so we can simply call its .join() method to concatenate the strings it contains, passing an empty string as argument (otherwise it defaults to concatenate strings adding a comma between them):

取而代之的是,我们可以使用这种语法,在扩展运算符( ... )后面加上我们要使用的参数名称。 在函数内部,参数是一个数组,因此我们可以简单地调用其.join()方法来连接包含的字符串,并传递一个空字符串作为参数(否则,默认情况下是将字符串连接起来,并在它们之间添加逗号):

const join = (...strings) => {
  return strings.join('')
}

In our case we can also simplify this using the implicit return syntax available in arrow functions:

在我们的案例中,我们还可以使用箭头函数中可用的隐式返回语法来简化此操作:

const join = (...strings) => strings.join('')

and we can call this in the same way we did before:

我们可以像以前一样调用它:

join('hi', ' flavio') // 'hi flavio'
join('hi', ' flavio', ' it', ' is', ' a', ' beautiful day!') // ''hi flavio it is a beautiful day!'

翻译自: https://flaviocopes.com/how-to-unlimited-function-parameters-js/

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值