如何在 JavaScript 函数中传递第 n 个可选参数而不传递先前的参数? [英] How to pass the nth optional argument without passing prior arguments in JavaScript functions?

查看:83
本文介绍了如何在 JavaScript 函数中传递第 n 个可选参数而不传递先前的参数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我们有一个如下所示的函数,我想对第一个参数 a 使用默认值,为第二个参数 b 使用自定义值.

So imagine we got a function like below, and I want to use the default value for the first parameter a and a custom value for second parameter b.

const func = (a = 1 , b = 2) => {
    console.log("a is equal to " + a, " and b is equal to " + b)
}

我只想为参数 b 传递一个值.像这样:

I want to just pass one value for parameter b. something like this:

func(b : 7);
// I want it to print: a is equal to 1 and b is equal to 7

如何在 JavaScript 中实现它?

How can I achieve it in JavaScript?

推荐答案

您修改函数以接收一个对象,然后在该对象中您还可以为某些属性(如 a 和 b)定义默认值.

You modify your function to receive an object and then inside that object you can also define default values for some properties like a and b.

const func = ({ a = 1, b = 2 }) => {
  console.log("a is equal to " + a, " and b is equal to " + b)
}

func({b: 3})

这篇关于如何在 JavaScript 函数中传递第 n 个可选参数而不传递先前的参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆