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/