我希望JavaScript函数具有可选的参数,我在这些参数上设置了默认值,如果未定义值,则使用这些参数(如果传递了值,则忽略这些参数)。在Ruby中,您可以这样做:

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

这在JavaScript中有效吗?

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

当前回答

函数throwIfNoValue(){抛出新错误(“缺少参数”);}函数foo(argValue=throwIfNoValue()){返回argValue;}

这里foo()是一个函数,它有一个名为argValue的参数。如果我们在这里的函数调用中没有传递任何信息,那么将调用throwIfNoValue()函数,并将返回的结果分配给唯一的参数argValue。这就是函数调用可以用作默认参数的方式。这使得代码更加简化和可读。

此示例取自此处

其他回答

是-证明:

函数read_file(file,delete_after=false){//代码console.log({file,delete_after});}//测试读取文件(“A”);read_file(“B”,true);read_file(“C”,false);

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

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

只是起作用。

参考:默认参数-MDN

如果没有传递值或未定义,则默认函数参数允许使用默认值初始化形式参数。

在ES6中,可以通过析构函数模拟默认命名参数:

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

// sample call using an object
myFor({ start: 3, end: 0 });

// also OK
myFor();
myFor({});

ES2015之前,

有很多种方法,但这是我的首选方法——它可以让你传递任何你想要的东西,包括false或null。(空类型==“对象”)

function foo(a, b) {
  a = typeof a !== 'undefined' ? a : 42;
  b = typeof b !== 'undefined' ? b : 'default_b';
  ...
}

我注意到一些回答提到,使用默认参数对其他浏览器来说是不可移植的,但可以公平地指出,对于对现代JS功能支持有限的浏览器,可以使用像Babel这样的转换器将代码转换为ES5语法。

因此:

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

将被翻译成这样(在Babel REPL->中尝试https://babeljs.io/repl/):

"use strict";

function read_file(file) {

  var delete_after =
    arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false;
  
  //Code...

}

当然,如果您无意使用转换,那么像其他人所演示的那样,在函数体中设置默认参数也是非常好的。

ES6:正如大多数答案中已经提到的,在ES6中,您可以简单地初始化一个参数和一个值。


ES5:大多数给出的答案对我来说都不够好,因为在某些情况下,我可能不得不向函数传递假值,例如0、null和undefined。要确定参数是否未定义,因为这是我传递的值,而不是未定义的值,因为根本没有定义,我执行以下操作:

function foo (param1, param2) {
   param1 = arguments.length >= 1 ? param1 : "default1";
   param2 = arguments.length >= 2 ? param2 : "default2";
}

我发现像这样简单的东西个人来说更加简洁和易读。

function pick(arg, def) {
   return (typeof arg == 'undefined' ? def : arg);
}

function myFunc(x) {
  x = pick(x, 'my default');
}