简体   繁体   中英

Javascript: assigning the second optional argument without assigning the first

I'm trying to create a function that has multiple optional arguments. I am then trying to only assign the second argument without having to also assign the first one.

function foo(bar, zar) {
  bar = bar || 5;
  zar = zar || 2;

  return bar * zar;
}

foo()      //10
foo(7)     //14
foo(7, 3)  //21
foo(zar=5) //10 <-- why is this not 25?

What is the best way to do this?

IMHO, the easiest way to handle this kind of situation is to instead use an object for the parameter, with default field values via the ES6 syntax.

 function foo({ bar = 5, zar = 2 } = {}) { console.log(bar * zar); } foo() //10 foo({ bar: 7 }) //14 foo({ bar: 7, zar: 3 }) //21 foo({ zar: 5 }) //25 

For reference, see: Default parameters and Object destructuring .

You could pass undefined for whatever parameters you would want to use as defaults.

foo(undefined, 5);

Also, if you are free to use ES6, you can simplify your function a little and declare your optional parameters like so:

function foo(bar = 5, zar = 2) { }

Use void 0 instead of the arguments you don't want to supply.

For example: foo(void 0,zar=5);

Any unfilled argument will be undefined .

You cannot pass the second parameter without passing the first, but you can pass undefined . In the function, you can check for undefine d and replace with a default value.

Alternately, you can use an object argument to imitate keyword arguments.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM