bug^君 2009-05-21 20:07 采纳率: 25%
浏览 658
已采纳

设置 JavaScript 函数的默认参数值

I would like a JavaScript function to have optional arguments which I set a default on, which gets used if the value isn't defined. In Ruby you can do it like this:

def read_file(file, delete_after = false)
  # code
end

Does this work in JavaScript?

function read_file(file, delete_after = false) {
  // Code
}

转载于:https://stackoverflow.com/questions/894860/set-a-default-parameter-value-for-a-javascript-function

  • 写回答

21条回答 默认 最新

  • 关注

    From ES6/ES2015, default parameters is in the language specification.

    function read_file(file, delete_after = false) {
      // Code
    }
    

    just works.

    Reference: Default Parameters - MDN

    Default function parameters allow formal parameters to be initialized with default values if no value or undefined is passed.

    You can also simulate default named parameters via destructuring:

    // the `= {}` below lets you call the function without any parameters
    function myFor({ start = 5, end = 1, step = -1 } = {}) { // (A)
        // Use the variables `start`, `end` and `step` here
        ···
    }
    

    Pre ES2015,

    There are a lot of ways, but this is my preferred method - it lets you pass in anything you want, including false or null. (typeof null == "object")

    function foo(a, b) {
      a = typeof a !== 'undefined' ? a : 42;
      b = typeof b !== 'undefined' ? b : 'default_b';
      ...
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(20条)

报告相同问题?

悬赏问题

  • ¥20 有人能用聚类分析帮我分析一下文本内容嘛
  • ¥15 请问Lammps做复合材料拉伸模拟,应力应变曲线问题
  • ¥30 python代码,帮调试
  • ¥15 #MATLAB仿真#车辆换道路径规划
  • ¥15 java 操作 elasticsearch 8.1 实现 索引的重建
  • ¥15 数据可视化Python
  • ¥15 要给毕业设计添加扫码登录的功能!!有偿
  • ¥15 kafka 分区副本增加会导致消息丢失或者不可用吗?
  • ¥15 微信公众号自制会员卡没有收款渠道啊
  • ¥100 Jenkins自动化部署—悬赏100元