函数参数的默认值

// ES5
function a (x, y) {
  x = x === undefined ? 1 : 1
  y = y === undefined ? 2 : y
  return x + y
}

console.log(a())
3
// ES6
function a (x = 1, y = 2) {
  return x + y
}

console.log(a())
3

默认参数还可以是前面参数的表达式

// ES6
function a (x = 1, y = x + x) {
  return x + y
}

console.log(a())
3

指定部分默认参数的值,不指定就用undifined

// ES6
function a (x = 1, y = x + x) {
  return x + y
}

console.log(a(undefined, 5))
6

在ES6中,函数名.length可以返回形参中非默认参数的个数

// ES6
function a (x = 1, y = x + x) {
  console.log(a.length)
}

console.log(a(undefined, 5))
0

 

posted @ 2020-04-21 23:24  AllenZhang_(*^▽^*)  阅读(133)  评论(0编辑  收藏  举报