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

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

这在JavaScript中有效吗?

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

当前回答

我注意到一些回答提到,使用默认参数对其他浏览器来说是不可移植的,但可以公平地指出,对于对现代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...

}

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

其他回答

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

只需使用未定义的显式比较。

function read_file(file, delete_after)
{
    if(delete_after === undefined) { delete_after = 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';
  ...
}

未来之声

将来,您将能够将一个对象“散布”到另一个对象(目前截至2019年,Edge不支持!)-演示如何将其用于良好的默认选项,而不考虑顺序:

功能测试(选项){var选项={//默认值url:'defaultURL',some:“somethingDefault”,//使用输入选项覆盖…选项};var body=document.getElementsByTagName('body')[0];body.innerHTML+='<br>'+options.url+':'+options.some;}测试();测试({});测试({url:'myURL'});测试({some:'somethingOfMine');测试({url:'overrideURL',some:'andSomething'});测试({url:'overrideURL',一些:'andSomething',额外:'noProblem'});

MDN参考:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_syntax

…同时,Edge支持的是Object.assign()(IE不支持,但我真的希望我们可以将IE留在后面:)

同样,你也可以这样做

功能测试(选项){var options=对象分配({//默认值url:'defaultURL',some:“somethingDefault”,},选项);//使用输入选项覆盖var body=document.getElementsByTagName('body')[0];body.innerHTML+='<br>'+options.url+':'+options.some;}测试();测试({});测试({url:'myURL'});测试({some:'somethingOfMine');测试({url:'overrideURL',some:'andSomething'});测试({url:'overrideURL',一些:'andSomething',额外:'noProblem'});

编辑:由于对常量选项的评论-在函数的其余部分使用常量选项的问题实际上并不是你不能做到这一点,而是你不能在它自己的声明中使用常量变量-你必须将输入命名调整为

function test(input_options){
   const options = {
     // defaults
     someKey:    'someDefaultValue',
     anotherKey: 'anotherDefaultValue',

     // merge-in input options
     ...input_options
   };

   // from now on use options with no problem
}
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];

    }
}