admin管理员组

文章数量:1244386

In PHP we can specify default value of variable in function like:

function myFunction(myDefaultVariable, myOtherVariable, myCheckVariable = "basic"){
    // so yeah, myDefaultVariable is required always,
    // same applies for myOtherVariable,
    // and myCheckVariable can be skipped in function call, because it has a default value already specified.
}

Is there something similar to this in JavaScript?

In PHP we can specify default value of variable in function like:

function myFunction(myDefaultVariable, myOtherVariable, myCheckVariable = "basic"){
    // so yeah, myDefaultVariable is required always,
    // same applies for myOtherVariable,
    // and myCheckVariable can be skipped in function call, because it has a default value already specified.
}

Is there something similar to this in JavaScript?

Share Improve this question asked Sep 7, 2010 at 7:24 tomsseisumstomsseisums 13.4k20 gold badges88 silver badges148 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 9

You don't need to pass all the variables in Javascript.

Although a less hacky way would be to use objects:

function foo(args) {
    var text = args.text || 'Bar';

    alert(text);
}

To call it:

foo({ text: 'Hello' }); // will alert "Hello"
foo(); // will alert "Bar" as it was assigned if args.text was null

not exactly, but you can simulate it by checking if a value was passed and setting a default, e.g.

optionalArg = (typeof optionalArg == "undefined")?'defaultValue':optionalArg

Note that technique like this works even when optionalArg is supplied but evaluates as false - something that a simpler idiom like optionalArg=optionalArg || 'default' fails on.

Also inside every function you can access to an array called arguments which will contain all the arguments passed to the function, you can use that to have functions with variable length argument lists.

None that I'm aware of:

But there are 2 ways to tackle this.

//1. function.arguments - this is advisable if you don't know the 
//   maximum number of passed arguments.

function foo() {
  var argv = foo.arguments;
  var argc = argv.length;
  for (var i = 0; i < argc; i++) {
    alert("Argument " + i + " = " + argv[i]);
   }
}

foo('hello', 'world');

//2. "Or" operator - this is good for functions where you know the
//   details of the optional variable(s).

function foo (word1, word2) {
   word2 = word2 || 'world';
   alert (word1 + ' ' + word2);
}

foo ('hello'); // Alerts "hello world"

本文标签: javascriptFunction required and notrequired variablesStack Overflow