Default parameter values have been introduced in ES6 in 2015, and are widely implemented in modern browsers.
默认参数值已在2015年的ES6中引入,并已在现代浏览器中广泛实现。
This is a doSomething
function which accepts param1
.
这是一个接受参数param1
的doSomething
函数。
const doSomething = (param1) => {
}
We can add a default value for param1
if the function is invoked without specifying a parameter:
如果在不指定参数的情况下调用函数,我们可以为param1
添加默认值:
const doSomething = (param1 = 'test') => {
}
This works for more parameters as well, of course:
当然,这也适用于更多参数:
const doSomething = (param1 = 'test', param2 = 'test2') => {
}
What if you have an unique object with parameters values in it?
如果您有一个带有参数值的唯一对象怎么办?
Once upon a time, if we had to pass an object of options to a function, in order to have default values of those options if one of them was not defined, you had to add a little bit of code inside the function:
曾几何时,如果必须将选项对象传递给函数,如果未定义其中一个选项,则要具有这些选项的默认值,则必须在函数内部添加一些代码:
const colorize = (options) => {
if (!options) {
options = {}
}
const color = ('color' in options) ? options.color : 'yellow'
...
}
With destructuring you can provide default values, which simplifies the code a lot:
通过解构,您可以提供默认值,从而大大简化了代码:
const colorize = ({ color = 'yellow' }) => {
...
}
If no object is passed when calling our colorize
function, similarly we can assign an empty object by default:
如果在调用我们的colorize
函数时没有传递任何对象,则类似地,我们可以默认分配一个空对象:
const spin = ({ color = 'yellow' } = {}) => {
...
}
翻译自: https://flaviocopes.com/how-to-set-default-parameter-values-javascript/