北城已荒凉 2009-05-21 20:07 采纳率: 0%
浏览 431
已采纳

设置 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条回答 默认 最新

  • 三生石@ 2009-05-21 20:10
    关注

    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条)

报告相同问题?

悬赏问题

  • ¥15 js调用html页面需要隐藏某个按钮
  • ¥15 ads仿真结果在圆图上是怎么读数的
  • ¥20 Cotex M3的调试和程序执行方式是什么样的?
  • ¥20 java项目连接sqlserver时报ssl相关错误
  • ¥15 一道python难题3
  • ¥15 牛顿斯科特系数表表示
  • ¥15 arduino 步进电机
  • ¥20 程序进入HardFault_Handler
  • ¥15 oracle集群安装出bug
  • ¥15 关于#python#的问题:自动化测试