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 badges4 Answers
Reset to default 4If 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
版权声明:本文标题:Passing Javascript an Empty Variable - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1742120011a2421650.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论