js能否给参数设置默认值?如test(hello="1");
php是可以这么做的,js要怎么做才能设置默认值参数?以下代码报错<script type="text/javascript">
function test(hello="1"){ //missing ) after formal parameters
alert(hello);

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

解决方案 »

  1.   

    <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(obj){    
            alert(obj);
        } 
    </script>
    <button onclick="test();">no parameter</button>
    <button onclick="test('2');">with parameter</button>
      

  3.   

    可以在函数里判断一下参数又没又值
    <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>