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

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

这在JavaScript中有效吗?

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

当前回答

为了展示我的技能(lol),即使没有下面的命名参数,也可以编写上述函数:

ES5及以上

function foo() {
    a = typeof arguments[0] !== 'undefined' ? a : 42;
    b = typeof arguments[1] !== 'undefined' ? b : 'default_b';
    ...
}

ES6及以上

function foo(...rest) {
    a = typeof rest[0] !== 'undefined' ? a : 42;
    b = typeof rest[1] !== 'undefined' ? b : 'default_b';
    ...
}

其他回答

从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';
  ...
}

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

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

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

如果出于某种原因,您不在ES6上,并且正在使用lodash,那么这里有一种通过_.defaultTo方法默认函数参数的简洁方法:

var fn=函数(a,b){a=_.defaultTo(a,'Hi')b=_.defaultTo(b,'妈妈!')控制台日志(a,b)}fn()//嗨,妈妈!fn(未定义,空)//嗨,妈妈!fn(NaN,NaN)//嗨,妈妈!fn(1)//1“妈妈!”fn(空,2)//高2fn(假,假)//假-假fn(0,2)//0 2<script src=“https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.min.js“></script>

如果当前值为NaN、null或undefined,将设置默认值

作为更新。。。使用ECMAScript 6,您最终可以在函数参数声明中设置默认值,如下所示:

function f (x, y = 7, z = 42) {
  return x + y + z
}

f(1) === 50

参考文件:http://es6-features.org/#DefaultParameterValues

function helloWorld(name, symbol = '!!!') {
    name = name || 'worlds';
    console.log('hello ' + name + symbol);
}

helloWorld(); // hello worlds!!!

helloWorld('john'); // hello john!!!

helloWorld('john', '(>.<)'); // hello john(>.<)

helloWorld('john', undefined); // hello john!!!

helloWorld(undefined, undefined); // hello worlds!!!