简体   繁体   中英

How to set default values for parameters of a JavaScript function and call it with less parameters?

I have a function

function test(name)
{

}

I call it with test("kanishka");

In one case, I want to pass two parameters ( name and age ) to this function:

test("kanishka",27);

In PHP, I can do this by setting a default value to age :

test(name , age = NULL)

Is there any way in JavaScript to do this?

I tried

test(name , age = NULL) 

but it gives errors.

I can declare 2 functions

test(name) and  test(name , age = NULL)

but it duplicates the code.

Or I can change my previous function call which took one parameter to two parameters, giving a default value for age :

test("kanishka" , 0)

but in this case I have to find all function call and change them.

Just changing the definition of the function will work

test(name, age)
{

}

All existing uses of the function will assign to age an undefined value..

Whenever you use a second parameter it will be assigned to the age parameter.

If you want a default value change the function to

test(name, age)
{
    age = (age === undefined) ? 0 : age; // change 0 to the default value you want..
}

basically you will do something like this

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

You can still call the method, even if you pass the wrong number of arguments. The "optional" argument will be set to undefined, which you can check for using an if statement.

You can use the arguments object which holds all arguments passed to a function - regardless of if they are defined or not...

test(name){
    var age = arguments[1] == undefined ? 0 : arguments[1]
    // do stuff here
}

You can either declare the function with the 2 arguments:

function test(name, age) {
   //...
}
test("James"); //age will be undefined
test("James", 22); //age will be 22

Or you could forget about the parameters altogether and use the arguments object:

function test() {
    console.log(arguments[0]);
}

This way you can pass in as many arguments as you like, and access them through the arguments object.

The "standard" way to provide default values for methods is to check whether the arguments have been supplied at the start of the method body:

function test(name, age)
{
  age = typeof(age) != 'undefined' ? age : NULL;
  ...
}

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