zoukankan      html  css  js  c++  java
  • 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
    
  • 相关阅读:
    mysql数据库如何设置默认字符集
    vue初探(构建一个axios+java项目)
    mui中几种open页面的区别
    git版本控制的文件(没有图标标明)
    JDBC连接超时,针对连接不稳定,有时候能连上(登录),一会又报连接超时
    提升group by 的效率
    enum类型与tinyint,mysql数据库tinyint数据取出0和1的方法
    word.xml加变量赋值后格式损坏(类似发表评论,脚本符号<>&)
    iOS--全局断点的设置
    23Properties(配置文件)
  • 原文地址:https://www.cnblogs.com/Leophen/p/14790467.html
Copyright © 2011-2022 走看看