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

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

这在JavaScript中有效吗?

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

当前回答

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

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

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

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

其他回答

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

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

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

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

function read_file(file, delete_after) {
    delete_after = delete_after || "my default here";
    //rest of code
}

如果delete_after的值不是假值,则将其赋值给delete_aafter,否则将赋值字符串“我的默认值”。有关更多详细信息,请查看DougCrockford的语言调查,并查看操作员部分。

如果要传入假值,即false、null、undefined、0或“”,则此方法不起作用。如果需要传入假值,则需要使用Tom Ritter的答案中的方法。

当处理函数的多个参数时,允许使用者在对象中传递参数参数,然后将这些值与包含函数默认值的对象合并通常是有用的

function read_file(values) {
    values = merge({ 
        delete_after : "my default here"
    }, values || {});

    // rest of code
}

// simple implementation based on $.extend() from jQuery
function merge() {
    var obj, name, copy,
        target = arguments[0] || {},
        i = 1,
        length = arguments.length;

    for (; i < length; i++) {
        if ((obj = arguments[i]) != null) {
            for (name in obj) {
                copy = obj[name];

                if (target === copy) {
                    continue;
                }
                else if (copy !== undefined) {
                    target[name] = copy;
                }
            }
        }
    }

    return target;
};

使用

// will use the default delete_after value
read_file({ file: "my file" }); 

// will override default delete_after value
read_file({ file: "my file", delete_after: "my value" }); 

根据语法

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

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

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

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

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

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

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

function myfunc(a,b=10)

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

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

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