JS 函数参数默认值、Arguments 和 Rest parameter

一、ES 5 中函数默认值写法

function total(x, y, z) {
  if (y === undefined) {
    y = 2
  }
  if (z === undefined) {
    z = 3
  }
  return x + y + z
}

console.log(total())                  // NaN
console.log(total(1))                 // 6
console.log(total(1, 10))             // 14
console.log(total(1, undefined, 100)) // 103
console.log(total(1, 10, 100))        // 111

二、ES 6 中函数默认值写法

function total(x, y = 2, z = 3) {
  return x + y + z
}

console.log(total())                  // NaN
console.log(total(1))                 // 6
console.log(total(1, 10))             // 14
console.log(total(1, undefined, 100)) // 103
console.log(total(1, 10, 100))        // 111

参数设置注意事项

  • 有默认值的参数要往后靠
  • 参数的默认值可以是其它参数的运算表达式(如 z = x+y)

三、arguments 获取传入参数的个数

用来表示当前函数传入的参数,作为伪数组输出(可通过 Array.from 转换成数组)
示例:

function total(x, y = 2, z = 3) {
  return arguments
}

console.log(total(1))

输出:

通过以上代码可知,默认参数不存在 arguments 中

function total(x, y = 2, z = 3) {
  return arguments.length
}

console.log(total(1))                 // 1
console.log(total(1, 10))             // 2
console.log(total(1, undefined, 100)) // 3
console.log(total(1, 10, 100))        // 3

通过以上代码可知,undefined 作为参数传入时,也存在于 arguments 中

function total(x, y = 2, z = 3) {
  return arguments.length
}

console.log(total(1, 10, 100, 1000))  // 4

通过以上代码可知,arguments 只要传入的参数都计算在内

四、.length 获取函数没有默认值的参数

function totalA(x, y = 2, z = 3) {
  return x + y + z
}
function totalB(x, y, z = 3) {
  return x + y + z
}

console.log(totalA.length)  // 1
console.log(totalB.length)  // 2

五、Rest parameter 获取函数中被执行的参数

function total(...num) {
  let count = 0
  num.forEach(item => {
    count += item * 1
  })
  return count
}

console.log(total(1, 2, 3, 4))  // 10

也可以独立出某个参数,例如:

function total(base, ...num) {
  let count = 0
  num.forEach(item => {
    count += item * 1
  })
  return base * count
}

console.log(total(10, 1, 2, 3))  // 60
posted @ 2021-02-16 16:47  Leophen  阅读(277)  评论(0编辑  收藏  举报