如何在 JavaScript 中检查空值?
如何在 JavaScript 中检查空值?我写了下面的代码,但它不起作用。
if (pass == null || cpass == null || email == null || cemail == null || user == null) {
alert("fill all columns");
return false;
}
How can I check for null values in JavaScript? I wrote the code below but it didn't work.
if (pass == null || cpass == null || email == null || cemail == null || user == null) {
alert("fill all columns");
return false;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(24)
JavaScript 在检查“null”值方面非常灵活。我猜您实际上是在寻找空字符串,在这种情况下,这个更简单的代码将起作用:
它将检查空字符串 (
""
),null
, <代码>未定义,<代码>假和数字<代码>0和<代码>NaN。请注意,如果您专门检查数字,则使用此方法错过
0
是一个常见错误,并且首选num !== 0
(或num !== -1
或~num
(也检查-1
的黑客代码))对于返回-1
的函数>,例如indexOf
)。JavaScript is very flexible with regards to checking for "null" values. I'm guessing you're actually looking for empty strings, in which case this simpler code will work:
Which will check for empty strings (
""
),null
,undefined
,false
and the numbers0
andNaN
.Please note that if you are specifically checking for numbers, it is a common mistake to miss
0
with this method, andnum !== 0
is preferred (ornum !== -1
or~num
(hacky code that also checks against-1
)) for functions that return-1
, e.g.indexOf
).要专门检查 null,您可以使用:
此测试将ONLY通过
null
,而不会通过""、
未定义
、false
、0
或NaN
。此外,我还为每个“类似 false”的值(对于
!variable
返回 true 的值)提供了绝对检查。请注意,对于某些绝对检查,您需要实现使用
absolute equals: ===
和typeof
。我在这里创建了一个 JSFiddle 来显示所有正在运行的单独测试
以下是每次检查的输出:
如您所见,针对
NaN
进行测试有点困难;To check for null SPECIFICALLY you would use this:
This test will ONLY pass for
null
and will not pass for""
,undefined
,false
,0
, orNaN
.Additionally, I've provided absolute checks for each "false-like" value (one that would return true for
!variable
).Note, for some of the absolute checks, you will need to implement use of the
absolutely equals: ===
andtypeof
.I've created a JSFiddle here to show all of the individual tests working
Here is the output of each check:
As you can see, it's a little more difficult to test against
NaN
;只需将所有位置的
==
替换为===
即可。==
是松散或抽象的相等比较===
是严格的相等比较请参阅 MDN 文章 相等性比较和相同性了解更多详细信息。
just replace the
==
with===
in all places.==
is a loose or abstract equality comparison===
is a strict equality comparisonSee the MDN article on Equality comparisons and sameness for more detail.
您可以检查某个值是否为空,如下所示
额外奖励:为什么
===
比==
更清晰(来源)a == b
a === b
You can check if some value is null as follows
BONUS: Why
===
is more clear than==
(source)a == b
a === b
严格相等运算符:-
我们可以通过
===
检查null,只要使用
if
,如果值不<,则计算结果为true /strong>:
Strict equality operator:-
We can check null by
===
Just by using
if
will evaluate to true if value is not:
乍一看,它看起来像是覆盖范围和严格性之间的简单权衡。
==
涵盖了多个值,可以用更少的代码处理更多的场景。===
是最严格的,这使得它可以预测。可预测性总是获胜,这似乎使
===
成为一种万能的解决方案。但是这是错误的。尽管
===
是可预测的,但它并不总是产生可预测的代码,因为它忽略了场景。一般
==
对 null 检查的工作更可预测:一般来说,
null
和undefined
两者的意思是相同的:“缺少某些东西”。为了可预测性,您需要检查这两个值。然后== null
就完成了完美的工作,因为它完全涵盖了这两个值。 (即== null
相当于=== null && === undefined
)在特殊情况下,您 < strong>确实希望在
null
和undefined
之间有明确的区别。在这些情况下,您最好使用严格的=== undefined
或=== null
。 (例如,缺失/忽略/跳过和空/清除/删除之间的区别。)但这种情况罕见。这不仅罕见,而且是应该避免的。您无法在传统数据库中存储
undefined
。由于互操作性原因,您也不应该在 API 设计中依赖undefined
值。但即使你根本不做区分,你也不能假设未定义
不会发生。我们周围的人都会间接采取概括的行动>null
/undefined
(这就是为什么像 这被关闭为“固执己见”。)。那么,回到你的问题。使用
== null
没有任何问题。它确实做了它应该做的事情。At first sight, it looks like a simple trade-off between coverage and strictness.
==
covers multiple values, can handle more scenarios in less code.===
is the most strict, and that makes it predictable.Predictability always wins, and that appears to make
===
a one-fits-all solution.But it is wrong. Even though
===
is predictable, it does not always result in predictable code, because it overlooks scenarios.In general
==
does a more predictable job for null checks:In general,
null
andundefined
both mean the same thing: "something's missing". For predictability, you need to check both values. And then== null
does a perfect job, because it covers exactly those 2 values. (i.e.== null
is equivalent to=== null && === undefined
)In exceptional cases you do want a clear distinction between
null
andundefined
. And in those cases you're better of with a strict=== undefined
or=== null
. (e.g. a distinction between missing/ignore/skip and empty/clear/remove.) But it is rare.It is not only rare, it's something to avoid. You can't store
undefined
in a traditional database. And you shouldn't rely onundefined
values in your API designs neither, due to interopability reasons. But even when you don't make a distinction at all, you can't assume thatundefined
won't happen. People all around us indirectly take actions that generalizenull
/undefined
(which is why questions like this are closed as "opinionated".).So, to get back to your question. There's nothing wrong with using
== null
. It does exactly what it should do.通过显式检查
null
但使用简化的语法来改进已接受的答案:Improvement over the accepted answer by explicitly checking for
null
but with a simplified syntax:首先,您有一个没有函数体的 return 语句。这很可能会引发错误。
进行检查的一种更简洁的方法是简单地使用 !操作员:
Firstly, you have a return statement without a function body. Chances are that that will throw an error.
A cleaner way to do your check would be to simply use the ! operator:
你可以使用 try catch 最后,
你也可以
抛出
你自己的错误。请参阅此。you can use try catch finally
you can also
throw
your own errors. See this.在 JavaScript 中,没有字符串等于
null
。也许您希望当
pass
为空字符串时pass == null
为 true,因为您知道松散相等运算符==
执行某些类型的类型强制。例如,此表达式为 true:
相反,严格相等运算符
===
表示这是 false:鉴于
''
和0
> 是松散相等的,您可能会合理地推测''
和null
是松散相等的。然而,事实并非如此。此表达式为 false:
将任何字符串与
null
进行比较的结果为 false。因此,pass == null
和所有其他测试始终为 false,并且用户永远不会收到警报。要修复您的代码,请将每个值与空字符串进行比较:
如果您确定
pass
是一个字符串,则pass == ''
也将起作用,因为只有一个空字符串string 松散地等于空字符串。另一方面,一些专家表示,在 JavaScript 中始终使用严格相等是一个好习惯,除非您特别想要执行松散相等运算符执行的类型强制。如果您想知道哪些值对松散相等,请参阅 关于此主题的 Mozilla 文章。
In JavaScript, no string is equal to
null
.Maybe you expected
pass == null
to be true whenpass
is an empty string because you're aware that the loose equality operator==
performs certain kinds of type coercion.For example, this expression is true:
In contrast, the strict equality operator
===
says that this is false:Given that
''
and0
are loosely equal, you might reasonably conjecture that''
andnull
are loosely equal. However, they are not.This expression is false:
The result of comparing any string to
null
is false. Therefore,pass == null
and all your other tests are always false, and the user never gets the alert.To fix your code, compare each value to the empty string:
If you're certain that
pass
is a string,pass == ''
will also work because only an empty string is loosely equal to the empty string. On the other hand, some experts say that it's a good practice to always use strict equality in JavaScript unless you specifically want to do the type coercion that the loose equality operator performs.If you want to know what pairs of values are loosely equal, see the table "Sameness comparisons" in the Mozilla article on this topic.
要检查 JavaScript 中的 undefined 和 null,您只需编写以下内容:
to check for undefined and null in javascript you need just to write the following :
实际上我认为你可能需要使用
if(值!== null &&值!==未定义)
因为如果您使用
if (value)
您也可能会过滤 0 或 false 值。考虑这两个函数:
在我的情况下,我只需要检查值是否为 null 和未定义,我不想过滤
0
或false
或' '
值。所以我使用了第二个测试,但是您可能也需要过滤它们,这可能会导致您使用第一个测试。Actually I think you may need to use
if (value !== null && value !== undefined)
because if you use
if (value)
you may also filter 0 or false values.Consider these two functions:
In my situation, I just needed to check if the value is null and undefined and I did not want to filter
0
orfalse
or''
values. so I used the second test, but you may need to filter them too which may cause you to use first test.'
Object.is()
' 方法可用于确定两个值是否相同。因此,您可以使用它来检查对象是否为 null。检查空值
检查未定义值(已声明变量,但尚未赋值。)
如果对象尚未声明,则不能使用。作为替代方案,您可以尝试以下操作:
Mozilla Object.is():
https://developer.mozilla.org/ en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is
The '
Object.is()
' method can be used to determine if two values are the same value. So, you can use it to check whether the object is null or not.Check for null values
Check for undefined values (A variable has been declared, but a value has not been assigned.)
If the object has not been declared, this cannot be used. As an alternative, you may try this:
Mozilla Object.is():
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is
这是对 WebWanderer 关于检查 NaN 的解决方案的评论(我还没有足够的代表来发表正式评论)。解决方案如下所示,
但对于有理数会失败,因为有理数会四舍五入到
0
,例如variable = 0.1
。更好的测试是:This is a comment on WebWanderer's solution regarding checking for NaN (I don't have enough rep yet to leave a formal comment). The solution reads as
but this will fail for rational numbers which would round to
0
, such asvariable = 0.1
. A better test would be:您可以使用lodash模块检查值是否为空或未定义
参考链接:https://lodash.com/docs/ #isNil
You can use lodash module to check value is null or undefined
Reference link: https://lodash.com/docs/#isNil
据我所知,在JAVASCRIPT中,当声明变量但尚未赋值时,其类型为
未定义
。因此我们可以检查变量,即使它是一个持有某些实例代替值的对象
。创建一个返回
true
的辅助方法来检查无效性,并在您的 API 中使用它。检查变量是否为空的辅助函数:
尝试捕获异常 API 调用:
一些测试用例:
AFAIK in JAVASCRIPT when a variable is declared but has not assigned value, its type is
undefined
. so we can check variable even if it would be anobject
holding some instance in place of value.create a helper method for checking nullity that returns
true
and use it in your API.helper function to check if variable is empty:
try-catch exceptional API call:
some test cases:
我找到了另一种方法来测试该值是否为 null:
null
同时充当number
和object
。比较null >= 0
或null <= 0
结果为true
。比较null === 0
或null > 0
或null < 0
将导致 false。但由于null
也是一个对象,我们可以将其检测为 null。我做了一个更复杂的函数 natureof ,它会比 typeof 做得更好,并且可以被告知要包含哪些类型或保持分组
I found a another way to test if the value is null:
null
acts as anumber
andobject
at the same time. Comparingnull >= 0
ornull <= 0
results intrue
. Comparingnull === 0
ornull > 0
ornull < 0
will result in false. But asnull
is also an object we can detect it as a null.I made a more complex function natureof witch will do better than typeof and can be told what types to include or keep grouped
我制作了这个非常简单的函数,它产生了奇迹:
路线是任何可以爆炸的价值链。我将它用于 jQuery/cheerio 和对象等。
示例 1:像这样的简单对象
const testObj = {items: [{ val: 'haya' }, { val: null }, { val: 'hum!' }];};
。但它可能是一个非常大的物体,我们甚至还没有制造出来。所以我传递它:
当然,如果您愿意,您可以使用
null
或'No value'
...无论您需要什么。通常,如果未找到,DOM 查询或 jQuery 选择器可能会抛出错误。但使用类似的东西:
I made this very simple function that works wonders:
The route is whatever chain of values that can blow up. I use it for jQuery/cheerio and objects and such.
Examples 1: a simple object such as this
const testObj = {items: [{ val: 'haya' }, { val: null }, { val: 'hum!' }];};
.But it could be a very large object that we haven't even made. So I pass it through:
Of course if you prefer you can use
null
or'No value'
... Whatever suit your needs.Usually a DOM query or a jQuery selector may throw an error if it's not found. But using something like:
空值的简单解决方案:
Simple Solution for empty values:
这是一个非常非人类的代码。但有效:
只要尝试一下即可帮助找到答案
This is a very non-human code. But works:
Just try it out and help the answer
与操作员进行可选检查怎么样?
例如:
What about optional check with operator ?
for example:
试试这个:
Try this:
如果布尔值来自数据库,这将不起作用
例如:
This will not work in case of Boolean values coming from DB
for ex:
检查错误条件:
Checking error conditions: