检查null或未定义 [英] Checking for null or undefined

查看:74
本文介绍了检查null或未定义的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

尽管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.

Also, I know that

if (value == null) {
}

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

if (value == null) {
}

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 == 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.

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 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.

The details of == are here: Abstract Equality Comparison.

这篇关于检查null或未定义的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆