简体   繁体   中英

Shorthand way to check for function parameters

In my code, I have a function that creates a new map given a few parameters. I want to make it so that if no parameters are passed, some default values will be used.

Why won't this work:

 function create(a,b,c) {
   return new Map(a,b,c || 10,1,10); // create new map using a b c as parameters
   // or 10, 1, 10 if none entered.
}

 create();

Assume that there is a constructor function 'Map' that would accept and process these parameters.

What can i do besides having an if/else type check?

You can do it this way:

function create(a, b, c) {
     a = typeof a !== 'undefined' ? a : 10;
     b = typeof b !== 'undefined' ? b : 1;
     c = typeof c !== 'undefined' ? c : 10;
     return new Map(a, b, c);
}

Javascript does not offer default function value parametization.

The shortest way i know under some limitations is to use

<var> = <var> || <defaultvalue>;

So

Return new Map((a = a || 10), (b = b || 1), (c = c || 10));

However this way its hardly readable and you might want to consider moving the assignments before the constructor.

The limitation however is that all falsy values lead to the default being assigned which might be a problem for some numeric values.

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