参数默认值的位置

通常情况下,定义了默认值的参数,应该是函数的尾参,因为这样比较容易发现函数在调用时省略了那些参数。如果是非尾部参数设置默认值,这个参数实际上是无法省略的。

// example - 1 
function f(x = 1, y) {
  return [x, y]
}

f() // [1, undefined]
f(2) // [2, undefined]
f(, 1) // 报错
f(undefined, 1) // [1, 1]

// example - 2
function f(x, y = 5, z) {
  return [x, y, z]
}

f() // [undefined, 5, undefined]
f(1) // [1, 5, undefined]
f(1, , 2) // 报错

上面的代码中,有默认值的参数都不是尾参数。这时,无法只省略该参数,而不是省略它后面的参数,除非显式输入 undefined

如果传入 undefined ,将触发该参数等于默认值,null 则没有这个效果。

function foo(x = 5, y = 6) {
  console.log(x, y)
}

foo(undefined, null)

上面代码中,x 参数对应 undefined ,结果触发了默认值,y 参数等于 null ,就没有触发默认值

Last updated