admin管理员组

文章数量:1323738

How do I tell Javascript to use zero as a variable if the passed variable if empty? In PHP I can use the following.

<?php
   function test($var=0){
      echo $var;
   }
?>

So it would set $var to 0 if the passed variable was empty. I can't seem to figure this out in Javascript.

Thanks

How do I tell Javascript to use zero as a variable if the passed variable if empty? In PHP I can use the following.

<?php
   function test($var=0){
      echo $var;
   }
?>

So it would set $var to 0 if the passed variable was empty. I can't seem to figure this out in Javascript.

Thanks

Share Improve this question edited Mar 13, 2012 at 3:47 adeneo 318k29 gold badges404 silver badges391 bronze badges asked May 23, 2011 at 14:19 DoyleyDoyley 3211 gold badge4 silver badges18 bronze badges
Add a ment  | 

4 Answers 4

Reset to default 4

If you call a method without providing a value for one (or more) of the arguments, those arguments will be undefined.

Thus within the method you can test whether the variable is defined, and if not assign it a default value:

function test(arg) {
    if (typeof(arg) === 'undefined') {
        arg = "default"; // or whatever default value you want
    };

    // Rest of method
}

It's not very elegant, but Javascript doesn't have a nice native default-arguments syntax.

You can use the or operator to do this a bit shorter;

function myFunc(var)
{
 var = var || 0;
}

It strongly depends on what empty means for you and what values the argument is allowed to have.

An often used shortcut is

param = param || 0;

This will set param to 0 whenever param evaluates to false.

This should work:

function myFunc(var) {
   if (null == var)
      var = 0; 
}

本文标签: Passing Javascript an Empty VariableStack Overflow