Javascript Functions and default parameters, not working in IE and Chrome

前端 未结 5 1652
臣服心动
臣服心动 2020-12-01 02:22

I created a function like this:

function saveItem(andClose = false) {

}

It works fine in Firefox

In IE it gives this error on the

5条回答
  •  自闭症患者
    2020-12-01 03:03

    You can't do this, but you can instead do something like:

    function saveItem(andClose) {
       if(andClose === undefined) {
          andClose = false;
       }
    }
    

    This is often shortened to something like:

    function setName(name) {
      name = name || 'Bob';
    }
    

    Update

    The above is true for ECMAScript <= 5. ES6 has proposed Default parameters. So the above could instead read:

    function setName(name = 'Bob') {}
    

提交回复
热议问题