Set a default parameter value for a JavaScript fun

2018-12-31 03:41发布

I would like a JavaScript function to have optional arguments which I set a default on, which gets used if the value isn't defined. In Ruby you can do it like this:

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

Does this work in JavaScript?

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

21条回答
伤终究还是伤i
2楼-- · 2018-12-31 03:50
function read_file(file, delete_after) {
    delete_after = delete_after || "my default here";
    //rest of code
}

This assigns to delete_after the value of delete_after if it is not a falsey value otherwise it assigns the string "my default here". For more detail, check out Doug Crockford's survey of the language and check out the section on Operators.

This approach does not work if you want to pass in a falsey value i.e. false, null, undefined, 0 or "". If you require falsey values to be passed in you would need to use the method in Tom Ritter's answer.

When dealing with a number of parameters to a function, it is often useful to allow the consumer to pass the parameter arguments in an object and then merge these values with an object that contains the default values for the function

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

to use

// 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" }); 
查看更多
路过你的时光
3楼-- · 2018-12-31 03:50

I find something simple like this to be much more concise and readable personally.

function pick(arg, def) {
   return (typeof arg == 'undefined' ? def : arg);
}

function myFunc(x) {
  x = pick(x, 'my default');
} 
查看更多
爱死公子算了
4楼-- · 2018-12-31 03:50

As an update...with ECMAScript 6 you can FINALLY set default values in function parameter declarations like so:

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

f(1) === 50

As referenced by - http://es6-features.org/#DefaultParameterValues

查看更多
泛滥B
5楼-- · 2018-12-31 03:50

ES6: As already mentioned in most answers, in ES6, you can simply initialise a parameter along with a value.


ES5: Most of the given answers aren't good enough for me because there are occasions where I may have to pass falsey values such as 0, null and undefined to a function. To determine if a parameter is undefined because that's the value I passed instead of undefined due to not have been defined at all I do this:

function foo (param1, param2) {
   param1 = arguments.length >= 1 ? param1 : "default1";
   param2 = arguments.length >= 2 ? param2 : "default2";
}
查看更多
何处买醉
6楼-- · 2018-12-31 03:52

being a long time C++ developer (Rookie to web development :)), when I first came across this situation, I did the parameter assignment in the function definition, like it is mentioned in the question, as follows.

function myfunc(a,b=10)

But beware that it doesn't work consistently across browsers. For me it worked on chrome on my desktop, but did not work on chrome on android. Safer option, as many have mentioned above is -

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

Intention for this answer is not to repeat the same solutions, what others have already mentioned, but to inform that parameter assignment in the function definition may work on some browsers, but don't rely on it.

查看更多
伤终究还是伤i
7楼-- · 2018-12-31 03:55

From ES6/ES2015, default parameters is in the language specification.

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

just works.

Reference: Default Parameters - MDN

Default function parameters allow formal parameters to be initialized with default values if no value or undefined is passed.

You can also simulate default named parameters via destructuring:

// the `= {}` below lets you call the function without any parameters
function myFor({ start = 5, end = 1, step = -1 } = {}) { // (A)
    // Use the variables `start`, `end` and `step` here
    ···
}

Pre ES2015,

There are a lot of ways, but this is my preferred method - it lets you pass in anything you want, including false or null. (typeof null == "object")

function foo(a, b) {
  a = typeof a !== 'undefined' ? a : 42;
  b = typeof b !== 'undefined' ? b : 'default_b';
  ...
}
查看更多
登录 后发表回答