JS将默认参数作为在该函数内部定义的变量传递?

JS pass default parameter as a variable that is defined inside that function?

例如:

function mf(z, x c, lol = b) { // I need lol = azazaz
  let b = azazaz
  ...
}

而不是 lol = azazaz 我显然得到 b is not defined.

我能做什么:

function mf(z, x, c, lol = "b") { //parameter lol is a string
  let b = azazaz
  lol = eval(lol) //now lol = azazaz
  ...
}

我也可以这样做:

function mf(z, x, c, lol) { //parameter lol doesn't have default value
  b = azazaz
  if (lol == 0) {
    lol = b             //default value of lol = azazaz
  }
  ...
}

但是第一个看起来很不专业,第二个有额外的if语句,我也不想要。有没有更好的方法来做到这一点?

如果在函数内部定义变量不是硬性要求,您可能可以利用闭包来执行以下操作:

const b = 'azazaz';
function mf(z, x, c, lol = b) { 
 ...
}

或者,也许使用 'OR' 来避免 if

function mf(z, x, c, lol) { //parameter lol doesn't have default value
  let b = 'azazaz';
  lol = lol || b;
  ...
}

如果您需要更改参数并且 re-use 您必须 re-call 像这样的函数:

//every time function change lol and recall function
function mf(z, x, c, lol) {
  console.log('lol now is: ' + lol);
  lol++;
  if (lol <= 10) {
    mf(1, 2, 3, lol);
  }
}

mf(1, 2, 3, 0);