检查null或未定义 [英] Checking for null or undefined
问题描述
尽管JavaScript的 null
和 undefined
之间存在语义差异,但很多时候它们可以被视为相同.检查该值是否为null或未定义的首选方法是什么?
现在我正在执行以下操作:
if(typeof value ==="undefined" || value === null){//做一点事}
这很冗长.我当然可以为此创建一个函数并将其导入到任何地方,但我希望有一种更好的方法来实现这一点.
我也知道
if(value == null){}
将90%的时间完成工作,除非value为零...或false ...或许多可能导致模糊错误的隐式事物.
我也知道
if(value == null){}
除非值是零...或false ...或许多可能导致模糊错误的隐式事物,否则将90%的时间完成工作.
不,它可以100%地完成工作. == null
的唯一值是 null
和 undefined.
0 == null
为false." == undefined
为false. false == null
为false.等等,您正在将 == null
与虚假性混淆,这是完全不同的事情.
这并不是说,编写期望每个人都知道的代码是一个好主意.您可以很好地,清晰地检查已在使用的代码.是选择编写 value == null
还是当前正在使用的显式代码(或 if(value === undefined || value === null)
)是风格和内部惯例的问题.但是 value == null
会执行您所要求的操作:检查 value
是 null
还是 undefined
./p>
Which is pretty verbose. I could, of course, create a function for this and import everywhere, but I'm wishing that there's a better way to achieve this. Will get the job done 90% of the time, unless value is zero... or false... or a number of implicit things that can cause obscure bugs. Also, I know that Will get the job done 90% of the time, unless value is zero... or false... or a number of implicit things that can cause obscure bugs. No, it gets the job done 100% of the time. The only values that are That's not to say, though, that it's a good idea to write code expecting everyone to know that. You have a perfectly good, clear check in the code you're already using. Whether you choose to write The details of 这篇关于检查null或未定义的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋! ==
的详细信息在这里:Also, I know that if (value == null) {
}
if (value == null) {
}
== null
are null
and undefined.
0 == null
is false. "" == undefined
is false. false == null
is false. Etc. You're confusing == null
with falsiness, which is a very different thing.value == null
or the explicit one you're currently using (or if (value === undefined || value === null)
) is a matter of style and in-house convention. But value == null
does do what you've asked: Checks that value
is null
or undefined
.==
are here: Abstract Equality Comparison.