How to pass the nth optional argument without passing prior arguments in JavaScript functions? [duplicate]

扶醉桌前 提交于 2021-02-10 17:45:45

问题


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)
}

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

How can I achieve it in JavaScript?


回答1:


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})



回答2:


try to use RORO pattern, to pass object into function



来源:https://stackoverflow.com/questions/57040478/how-to-pass-the-nth-optional-argument-without-passing-prior-arguments-in-javascr

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!