6

I want to be able to do this in JavaScript:

function myFunction(one, two = 1) {
     // code
}

myFunction("foo", "2");

myFunction("bar");

I tried this and it doesn't work. I don't know how to call this type of parameters, could somebody point me in the right direction?

Thanks.

4

4 に答える 4

3
function foo(a, b)
 {
   a = typeof a !== 'undefined' ? a : 42;
   b = typeof b !== 'undefined' ? b : 'default_b';
   //...
 }

Possibly duplicate of Set a default parameter value for a JavaScript function

于 2012-10-28T17:08:59.953 に答える
2
function myFunction(one, two) {
     two = two || 1
}

To be more precise e.g. it may not work when two is zero, check for null or undefined e.g.

if (typeof two === "undefined") two = 1
于 2012-10-28T17:08:45.587 に答える
2

Use this :

function myFunction(one, two) {
   if (typeof two == 'undefined') two = 1;
   ...
}

Beware not to do the common mistake

two = two || 1;

because this wouldn't allow you to provide "" or 0.

于 2012-10-28T17:09:17.147 に答える
0

Try:

if ( typeof two === "undefined" ) two = 2;

or

two = typeof two !== "undefined" ? two : 2;

Undefined arguments will have the value undefined, which is a "falsy" value. We can test this falsyness, and change the value accordingly.

于 2012-10-28T17:08:38.613 に答える