您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

设置JavaScript函数的默认参数值

设置JavaScript函数的默认参数值

从ES6 / ES2015开始,认参数在语言规范中。

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

正常工作。

如果 传递 或 则函数参数允许使用认值初始化形式参数。

您还可以通过解构来模拟认的命名参数:

// 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
    ···
}

有很多方法,但这是我的首选方法-它使您可以传递所需的任何内容包括false或null。(typeof null == "object"

function foo(a, b) {
  a = typeof a !== 'undefined' ? a : 42;
  b = typeof b !== 'undefined' ? b : 'default_b';
  ...
}
javascript 2022/1/1 18:13:53 有560人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶