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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/22426147/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 23:08:31  来源:igfitidea点击:

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

javascript

提问by Aerodynamika

Suppose I have a function in JavaScript:

假设我在 JavaScript 中有一个函数:

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

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

如何设置如果没有传递变量,那么默认情况下它为空?

采纳答案by Ja?ck

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.

在调用函数时,JavaScript 对所需函数参数的数量不是很挑剔;声明中提到但未传递的任何参数都将设置为 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 fooif it's truthy, or 'default value'otherwise.

上面将输出值foo是否为真,'default value'否则。

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

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

foo如果它不是undefined,这将输出值,'default value'否则输出。

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.

foo如果传递了参数,这将输出(无论其类型如何)的值。

Further considerations

进一步的考虑

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

虽然undefined不可写,因为ES5,并不是所有的浏览器都如此警惕强制执行这一点。如果您对此感到担心,可以使用两种替代方法:

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

回答by Rahul Bhanushali

All the above will work for sure, but this is the simplest approach and I use this the most.

以上所有方法肯定都有效,但这是最简单的方法,我最常使用它。

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

回答by KooiInc

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:

或者,如果你需要一个防御0false等(和服务@Ketola),你可以编造这样的:

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

... this || thatis known as short circuit evaluation.

... this || that被称为短路评估

回答by John

Or a more friendly (IMO) option would be:

或者更友好(IMO)的选项是:

function getProfile( singleVariable )
{
    singleVariable = singleVariable || false;
    if (singleVariable) {
        alert('we have a var')
    }
    else {
        alert('nothing opassed');
    }
}
getProfile();
getProfile('tom');

Then when you start passing lots of parameters over, but want the function to be flexible you can do:

然后,当您开始传递大量参数,但希望函数灵活时,您可以执行以下操作:

function getProfile(params)
{
    params = params || {};

    if (params.username) {
        alert(params.username)
    }
    if (params.id) {
      alert(params.id);
    }
}
getProfile();
getProfile({username:'tom', id: 123654987});

Instead of

代替

function getProfile(singleVariable, otherVar, othervar2)
{
    singleVariable = singleVariable || false;
    otherVar = otherVar|| false;
    otherVar2 = singleVariable2 || false;

    if( singleVariable ){
        alert('we have a var')
    }
    else {
        alert('nothing opassed');
    }
}

getProfile('tom', false, 'smith');

That false is required and is annoying.. passing an abject is far more efficient

那个 false 是必需的而且很烦人..传递一个卑鄙的人更有效率

回答by melc

You can check the size of argumentsvariable,

您可以检查arguments变量的大小,

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions_and_function_scope/arguments

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions_and_function_scope/arguments

function something (variable) {
  if(arguments.length===0){console.log("variable is null");}
  else{
    console.log(variable);
  }
}

Also have a look here in order to check if the variable is null,

也看看here以检查变量是否为空,

How to determine if variable is 'undefined' or 'null'?

如何确定变量是“未定义”还是“空”?

回答by R3tep

Test the value of your variable like this:

像这样测试变量的值:

function something (variable) {
    variable = (typeof variable !== 'undefined') ? variable : null;
}