How to set a variable passed on to a function as null in JavaScript

Suppose I have a function in JavaScript:

function something (variable) {
    console.log(variable);
}

How do I set that if there is no variable passed, then it is null by default?


JavaScript isn't very picky when it comes to the number of required function arguments when you call a function; any arguments that are mentioned in the declaration but not passed will be set to the type undefined .

For example:

function test(foo)
{
    console.log(foo === undefined); // true
}

To set default values there are at least three options:

function test(foo)
{
    console.log(foo || 'default value');
}

The above will output the value of foo if it's truthy, or 'default value' otherwise.

function test(foo)
{
    console.log(foo === undefined ? foo : 'default value');
}

This will output the value of foo if it's not undefined , or 'default value' otherwise.

Lastly, you can count the number of arguments that were passed:

function test(foo)
{
    console.log(arguments.length > 0 ? foo : 'default value');
}

This will output the value of foo (regardless of its type) if an argument was passed.

Further considerations

Although undefined is not writeable since ES5, not all browsers will be so vigilant to enforce this. There are two alternatives you could use if you're worried about this:

foo === void 0;
typeof foo === 'undefined'; // also works for undeclared variables

以上所有内容都可以正常工作,但这是最简单的方法,我使用最多。

variable = variable ? variable : undefined; // you can use null as well

It should be as simple as:

function something (variable) {
    console.log(variable || null);
}

In general you can assign default values to parameters like this:

function something (somevar1, somevar2 /* ... somevarn */) {
    somevar1 = somevar1 || 'somevar1 not present';
    somevar1 = somevar2 || 2;
    somevar3 = somevar3 || {foo: 'bar', foobar: null}
    /* etc. */
}

Or, if you need a defence against 0 , false , etc. (and to serve @Ketola), you could cook up something like:

function something (somevar1) {
    somevar1 = ['', 0, false, null, undefined].indexOf(somevar1) > -1
               && null || somevar1;
}

... this || that ... this || that is known as short circuit evaluation .

链接地址: http://www.djcxy.com/p/76360.html

上一篇: 检查null或undefined

下一篇: 如何在JavaScript中将传递给函数的变量设置为null