357

我可以声明默认参数吗

function myFunc( a, b=0)
{
  // b is my optional parameter
}

在 JavaScript 中?

4

2 回答 2

618

使用 ES6:这现在是语言的一部分

function myFunc(a, b = 0) {
   // function body
}

请记住,ES6 会undefined根据真实性而非真实性检查值(因此只有真正的未定义值才会获得默认值 - 像 null 这样的虚假值不会默认)。


使用 ES5:

function myFunc(a,b) {
  b = b || 0;

  // b will be set either to b or to 0.
}

只要您明确传入的所有值都是真实的,这就会起作用。根据 MiniGod 的评论,不真实的价值观:null, undefined, 0, false, ''

在函数实际启动之前,看到 JavaScript 库对可选输入进行大量检查是很常见的。

于 2012-10-09T09:42:06.517 回答
97

更新

使用 ES6,这完全可以按照您描述的方式进行;可以在文档中找到详细说明。

旧答案

JavaScript 中的默认参数主要可以通过两种方式实现:

function myfunc(a, b)
{
    // use this if you specifically want to know if b was passed
    if (b === undefined) {
        // b was not passed
    }
    // use this if you know that a truthy value comparison will be enough
    if (b) {
        // b was passed and has truthy value
    } else {
        // b was not passed or has falsy value
    }
    // use this to set b to a default value (using truthy comparison)
    b = b || "default value";
}

该表达式b || "default value"计算值 AND 是否存在,如果不存在或为假,则b返回 的值。"default value"b

替代声明:

function myfunc(a)
{
    var b;

    // use this to determine whether b was passed or not
    if (arguments.length == 1) {
        // b was not passed
    } else {
        b = arguments[1]; // take second argument
    }
}

特殊的“数组”arguments在函数内部可用;它包含所有参数,从 index0开始N - 1(其中N是传递的参数数量)。

这通常用于支持未知数量的可选参数(相同类型);但是,最好陈述预期的论点!

进一步的考虑

尽管自 ES5 以来undefined不可,但已知某些浏览器不会强制执行此操作。如果您对此感到担心,可以使用两种替代方法:

b === void 0;
typeof b === 'undefined'; // also works for undeclared variables
于 2012-10-09T09:49:12.643 回答