Is it possible to set default parameter values for functio开发者_StackOverflow社区ns in JavaScript like with PHP?
function phpFunc($param='defvalue'){
echo $param;
}
phpFunc();
Would result in 'defvalue' being outputted...
Is this possible in javascript?
Thanks.
No, it's not possible. You would have to do something like this :
function jsFunc(param) {
param = typeof param == 'undefined' ? 'defvalue' : param;
return param;
}
alert( jsFunc() ); // shows defvalue
alert( jsFunc('Hello, world!'); // shows Hello, world!
Hope this helps!
Or just:
function jsFunc(param){
param = param || defValue;
return param;
}
精彩评论