javascript 在 NodeJS 中处理未定义变量的简单条件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/23372417/
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-28 00:46:17  来源:igfitidea点击:

Handling undefined variables simple conditions in NodeJS

javascript

提问by Samuel Bolduc

Given this function:

鉴于此功能:

var test = function(param1, param2_maybe_not_set) {
  var my_object = {};
  // code here...
}

What's the best, in your opinion?

在您看来,什么是最好的?

my_object.new_key = (param2_maybe_not_set === undefined) ? null : param2_maybe_not_set;

OR

或者

my_object.new_key = (param2_maybe_not_set === void 0) ? null : param2_maybe_not_set;

OR

或者

my_object.new_key = (typeof param2_maybe_not_set === 'undefined') ? null : param2_maybe_not_set;

Alternatively, would this shortened expression be correct?

或者,这个缩短的表达式是否正确?

my_object.new_key = param2_maybe_not_set || null;

All four methods work (in the NodeJS console at least). Also jsPerf doesn't show a big gap between any of these (http://jsperf.com/typeof-performance/8)

所有四种方法都有效(至少在 NodeJS 控制台中)。此外 jsPerf 没有显示出其中任何一个之间的大差距(http://jsperf.com/typeof-performance/8

Which one should be used, as a good practice?

作为一种好的做法,应该使用哪一个?

回答by voithos

They are not strictly equivalent, but can often be used interchangeably. Here are the major differences between them:

它们并非严格等效,但通常可以互换使用。以下是它们之间的主要区别:

  • x === undefined: this performs a strict-equality comparison between the value and undefined, meaning that onlya actual value of undefinedwill be true, whereas similar values like nullor 0will be false.

    In the case of a function call, this check does not differentiate between f(a)and f(a, undefined)(in fact, none of the examples will; to differentiate, you'll have to look at arguments).

  • x === void 0: this uses the voidkeyword, which evaluates anyexpression and returns undefined. This was mostly done in the olden days to prevent surprises from people redefining the global undefinedvariable, but is not so useful nowadays (ECMAScript 5 mandates that undefinedbe read-only)

  • typeof x === 'undefined': this uses the typeofkeyword, which has a unique ability - namely, that the operand is unevaluated. This means that something like typeof foobarbazreturns 'undefined'even if no such variable foobarbazexists at all. Contrast this with foobarbaz === undefined, which will throw a ReferenceError if the variable name has never been declared.

  • x || null: this is the simplest and probably most readable alternative. The ||operator is often used to "set defaults" on arguments, and can be chained like x || y || z || null.

    In most cases, this is the idiomatic technique used. However, note that ||performs implicit conversions, which means that any "falsy" values will trigger the next value (meaning that it can't differentiate between undefined, false, null, 0, '', and NaN). So, if your function expects to receive falsy values as arguments, it may be more prudent to explicitly check for undefined.

  • x === undefined:这在值和 之间执行严格相等的比较undefined,这意味着只有实际值undefinedwill true,而类似的值,如null0将是假的。

    在函数调用的情况下,此检查不区分f(a)f(a, undefined)(实际上,所有示例都不会区分;要区分,您必须查看arguments)。

  • x === void 0: 这使用void关键字,它计算任何表达式并返回undefined。这主要是在过去完成的,以防止人们重新定义全局undefined变量时出现意外,但现在不是那么有用(ECMAScript 5 要求undefined为只读

  • typeof x === 'undefined': 这使用了typeof关键字,它具有独特的能力 - 即操作数是未计算的。这意味着,类似typeof foobarbaz的回报'undefined',即使没有这样的变量foobarbaz存在于所有。将此与 对比foobarbaz === undefined,如果从未声明变量名称,它将抛出一个 ReferenceError。

  • x || null:这是最简单也可能是最易读的选择。该||操作通常被用来在参数“设置默认值”,并可以链接像x || y || z || null

    在大多数情况下,这是使用的惯用技术。然而,请注意,||执行隐式转换,这意味着,任何“falsy”值将触发的下一个值(这意味着它不能区分undefinedfalsenull0'',和NaN)。因此,如果您的函数希望接收虚假值作为参数,则显式检查undefined.

回答by E. Valencia

The option chosen to be an idiom in Javascript development to force a value for an unspecified argument is actually the last:

选择作为 Javascript 开发中的惯用语来强制未指定参数的值的选项实际上是最后一个:

my_object.new_key = param2_maybe_not_set || null;

So this one should be preferrable since a lot of Javascript developers will immediately get its purpose.

所以这个应该是首选,因为很多 Javascript 开发人员会立即明白它的目的。

Best.

最好的。