ES2015 / 2016'typeof varName ==='undefined`的方式? [英] ES2015/2016 way of 'typeof varName === 'undefined`?
问题描述
我现在正在沉溺于ES2015 +奢侈品和一些项目,我想知道我是否可以摆脱那些讨厌的拐杖来检查新仙境中的 undefined
。
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 undefined
in the new wonderland.
ES2015 +中是否有更短但仍然准确的 typeof varName ==='undefined'
?
Is there a shorter but still exact way to typeof varName === 'undefined'
in ES2015+ already?
当然我可以使用默认参数但这也是一种不必要的分配。
Of course I could use default parameters but this also feels like an unnecessary assignment.
function coolFn(a = null){
if (a===null) console.log("no a supplied");
}
推荐答案
只需检查 varName === undefined
。
在旧浏览器中,可以为全局 undefined
变量导致该测试失败,但在ES2015 +中现在是不可能的。
In older browsers it was possible to assign an alternate value to the global undefined
variable causing that test to fail, but in ES2015+ that's now impossible.
注意,没有办法区分显式传递 undefined
作为参数完全离开参数而不是通过查看 arguments.length
。
Note that there's no way to distinguish explicitly passing undefined
as a parameter from leaving the parameter out altogether other than by looking at arguments.length
.
这篇关于ES2015 / 2016'typeof varName ==='undefined`的方式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!