问题
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