javascript:在函数中定义变量

时间:2015-01-20 19:30:19

标签: javascript

在PHP中,我可以这样做:

public myFunction($variable=0) {
    //Do some stuff
}

在Javascript中,以下内容不起作用:

var myFunction = function(variable=0 )
{

    //do some stuff...

};

2 个答案:

答案 0 :(得分:4)

试试这个

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将在ES6中; ES5不允许这样做。

答案 1 :(得分:1)

使用ECMAScript 6,您可以执行此操作。

检查一个例子:

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

multiply(5); // 5

但这仍然是实验性的,今天只有Mozilla Firefox浏览器支持。

查看此链接,请参阅documentantion:

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