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

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

这在JavaScript中有效吗?

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

当前回答

作为一名长期的C++开发人员(web开发新手:),当我第一次遇到这种情况时,我在函数定义中进行了参数赋值,就像问题中提到的那样,如下所示。

function myfunc(a,b=10)

但要注意,它在不同浏览器之间并不一致。对我来说,它在我的桌面上运行,但在android上不运行。更安全的选择,正如上面提到的那样-

    function myfunc(a,b)
    {
    if (typeof(b)==='undefined') b = 10;
......
    }

这个答案的意图不是重复其他人已经提到的相同解决方案,而是告知函数定义中的参数分配可能在某些浏览器上有效,但不要依赖它。

其他回答

设置默认参数的另一种方法是使用参数的对象映射,而不是直接使用参数。例如

const defaultConfig = {
 category: 'Animals',
 legs: 4
};

function checkOrganism(props) {
 const category = props.category || defaultConfig.category;
 const legs = props.legs || defaultConfig.legs;
}

这样,很容易扩展参数,而不用担心参数长度不匹配。

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功能支持有限的浏览器,可以使用像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 [name]([param1[ = defaultValue1 ][, ..., paramN[ = defaultValueN ]]]) {
   statements
}

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

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。这种方法在编程上看起来没有吸引力,但具有向后兼容性。