如何在JavaScript中设置默认参数值

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.

这是一个接受参数param1doSomething函数。

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/

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值