我希望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];

    }
}

其他回答

在ECMAScript 6中,您实际上可以编写您所拥有的内容:

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

如果delete_after不存在或未定义,则会将其设置为false。您可以在Babel等转发器上使用像今天这样的ES6功能。

有关更多信息,请参阅MDN文章。

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

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

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

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

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

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

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

是-证明:

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

根据语法

function [name]([param1[ = defaultValue1 ][, ..., paramN[ = defaultValueN ]]]) {
   statements
}

您可以定义正式参数的默认值。还可以使用typeof函数检查未定义的值。