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

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

这在JavaScript中有效吗?

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

当前回答

是-证明:

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

其他回答

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

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

f(1) === 50

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

为了展示我的技能(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';
    ...
}

如果您想使用最新的ECMA6语法,请使用此选项:

函数myFunction(someValue=“这是默认值!”){console.log(“someValue-->”,someValue);}myFunction(“不是默认值”)//调用没有默认值的函数myFunction()//使用默认值调用函数

它被称为默认函数参数。如果没有传递值或未定义,它允许使用默认值初始化形式参数。注意:它不适用于Internet Explorer或较旧的浏览器。

为了获得最大可能的兼容性,请使用以下选项:

函数myFunction(someValue){someValue=(someValue==未定义)?“这是默认值!”:someValue;console.log(“someValue-->”,someValue);}myFunction(“不是默认值”)//调用没有默认值的函数myFunction()//使用默认值调用函数

这两个函数具有完全相同的行为,因为这些示例依赖于这样一个事实:如果在调用该函数时没有传递任何参数值,则参数变量将是未定义的。

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

    }
}

这个解决方案在js中很适用:

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