javascript: define a variable in a function

This question already has an answer here:

  • Is there a better way to do optional function parameters in JavaScript? [duplicate] 29 answers

  • Try this

    var myFunction = function(variable) {
      variable = variable || 0;
      // this variant works for all falsy values "", false, null, undefined...
      // if you need check only undefiend, use this variant 
      // variable = typeof(variable) == 'undefined' ? 0 : variable
    };
    

    Default function parameters will be in ES6; ES5 does not allow it.


    With ECMAScript 6 you can do this.

    Check an example:

    function multiply(a, b = 1) {
      return a*b;
    }
    
    multiply(5); // 5
    

    But this is still experimental and today is only supported by Mozilla Firefox browser.

    Check this link do see documentantion:

    https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Default_parameters#Browser_compatibility

    链接地址: http://www.djcxy.com/p/17280.html

    上一篇: JS如果不是一个变量

    下一篇: javascript:在函数中定义一个变量