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

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

这在JavaScript中有效吗?

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

当前回答

从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 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!!!

为了展示我的技能(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+,则可以按以下方式设置默认参数:

功能测试(foo=1,bar=2){console.log(foo,bar);}测试(5);//foo被覆盖,bar保持默认参数

如果需要ES5语法,可以按以下方式执行:

功能测试(foo,bar){foo=foo||2;bar=bar||0;console.log(foo,bar);}测试(5);//foo被覆盖,bar保持默认参数

在上述语法中,使用OR运算符。如果可以将第一个值转换为真,OR运算符总是返回第一个值,如果不能,则返回右手边的值。当在没有相应参数的情况下调用函数时,JS引擎将参数变量(在我们的示例中为bar)设置为undefined。undefined然后转换为false,因此OR运算符返回值0。

export const getfilesize = (bytes, decimals = 2) => {
    if (bytes === 0){ 
        return '0 Bytes';
    }else{
        const k = 1024;
        const dm = decimals < 0 ? 0 : decimals;
        const sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'];
        const i = Math.floor(Math.log(bytes) / Math.log(k));
        return parseFloat((bytes / Math.pow(k, i)).toFixed(dm)) + ' ' + sizes[i];

    }
}

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


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

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