js能否给参数设置默认值?

<script type="text/javascript">

function test(hello="1"){ //missing ) after formal parameters alert(hello); } </script><button onclick="test();">
<button onclick="test();">no parameter</button>

<button onclick="test('2');">with parameter</button>

解决办法1:
  HTML code
<script type="text/javascript">
function test(hello){ hello = hello ||"1"; alert(hello); }
</script>
<button onclick="test();">no parameter</button>
<button onclick="test('2');">with parameter</button>
 
解决办法2:

可以在函数里判断一下参数又没又值
<script type='text/javascript'>
function test(hello) {
if(!!hello){
alert('参数有值,值为:' + hello);
} else {
alert('参数没值,默认为:1');
}
}
</script>
<button onclick="test();">no parameter</button>
<button onclick="test('2');">with parameter</button>
 
 

posted @ 2012-09-18 14:13  小泥巴1024  阅读(463)  评论(0编辑  收藏  举报