喵-见缝插针 2009-05-21 20:07 采纳率: 0%
浏览 665
已采纳

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

  • Didn"t forge 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 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥15 c++头文件不能识别CDialog