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

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

这在JavaScript中有效吗?

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

当前回答

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];

    }
}

其他回答

是的,这将在Javascript中工作。您也可以这样做:

function func(a=10,b=20)
{
    alert (a+' and '+b);
}

func(); // Result: 10 and 20

func(12); // Result: 12 and 20

func(22,25); // Result: 22 and 25

对于任何有兴趣在MicrosoftEdge中使用代码的人,不要在函数参数中使用默认值。

function read_file(file, delete_after = false) {
    #code
}

在该示例中,Edge将抛出错误“Expected')'”

为了避免这种使用

function read_file(file, delete_after) {
  if(delete_after == undefined)
  {
    delete_after = false;
  }
  #code
}

截至2016年8月8日,这仍然是一个问题

如果您使用的是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。

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

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

function myFunc(x) {
  x = pick(x, 'my default');
} 
def read_file(file, delete_after = false)
  # code
end

以下代码可能在这种情况下工作,包括ECMAScript 6(ES6)以及早期版本。

函数read_file(文件,删除后){if(delete_after==未定义)delete_after=false//默认值console.log('delete_after=',delete_after);}read_file('text1.txt',true);读取文件('text2.txt');

由于语言中的默认值在调用时跳过函数的参数值时起作用,因此在JavaScript中它被分配给undefined。这种方法在编程上看起来没有吸引力,但具有向后兼容性。