Javascript ES2015/2016 的 'typeof varName === 'undefined` 方式?

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

ES2015/2016 way of 'typeof varName === 'undefined`?

javascriptecmascript-6ecmascript-2016

提问by Hedge

I'm wallowing in ES2015+ luxury with a few projects right now and am wondering whether I can get rid of the much hated crutch to check for undefinedin the new wonderland.

我现在正在沉迷于 ES2015+ 的奢华和一些项目,我想知道我是否可以摆脱令人讨厌的拐杖来检查undefined新的仙境。

Is there a shorter but still exact way to typeof varName === 'undefined'in ES2015+ already?

typeof varName === 'undefined'在 ES2015+ 中是否有更短但仍然准确的方法?

Of course I could use default parametersbut this also feels like an unnecessary assignment.

当然我可以使用默认参数,但这也感觉像是一个不必要的分配。

function coolFn(a = null){
   if (a===null) console.log("no a supplied");
}

回答by Alnitak

Just check for varName === undefined.

只需检查varName === undefined.

In older browsers it was possible to assign an alternate value to the global undefinedvariable causing that test to fail, but in ES2015+ that's now impossible.

在较旧的浏览器中,可以为全局undefined变量分配一个替代值,导致该测试失败,但在 ES2015+ 中,这是不可能的。

Note that there's no way to distinguish explicitly passing undefinedas a parameter from leaving the parameter out altogether other than by looking at arguments.length.

请注意,undefined除了查看arguments.length.

回答by Oriol

The only case where typeof varName === 'undefined'is useful is when you don't know whether the variable varNamehas been declared.

唯一typeof varName === 'undefined'有用的情况是您不知道变量varName是否已声明。

And IMO if you don't know whether your variables are declared, your code has serious problems.

如果你不知道你的变量是否被声明,你的代码就有严重的问题。

In other cases you have better options:

在其他情况下,您有更好的选择:

  • varName === void 0

    This will detect whether varNameis undefined.

    voidis an operator which receives an argument (you can use whatever instead of 0), and returns undefined.

  • varName === undefined

    This shoulddetect whether varNameis undefined.

    However, be aware the global undefinedcould have been overwritten (before ES5) or shadowed with another value. Therefore I prefer void, which is also shorter.

  • varName == null

    This will detect whether varNameis undefined or is null.

  • !varName

    This will detect whether varNameis falsy (undefined, null, 0, empty string, NaN, false).

  • varName === void 0

    这将检测是否varName未定义。

    void是一个运算符,它接收一个参数(你可以使用任何东西代替0),并返回 undefined。

  • varName === undefined

    应该检测是否varName未定义。

    但是,请注意全局undefined可能已被覆盖(在 ES5 之前)或被另一个值遮蔽。因此我更喜欢void,它也更短。

  • varName == null

    这将检测是否varName未定义或为空。

  • !varName

    这将检测是否varName为假(未定义、空、0、空字符串、NaN、假)。