How do I check for null values in JavaScript?(如何在 JavaScript 中检查 null 值?)
问题描述
如何在 JavaScript 中检查空值?我写了下面的代码,但是没有用.
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;
}
我如何在我的 JavaScript 程序中发现错误?
And how can I find errors in my JavaScript programs?
推荐答案
JavaScript 在检查null"方面非常灵活.价值观.我猜你实际上是在寻找空字符串,在这种情况下,这个更简单的代码会起作用:
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:
if(!pass || !cpass || !email || !cemail || !user){
它将检查空字符串 (""
)、null
、undefined
、false
和数字 0
和 NaN
.
Which will check for empty strings (""
), null
, undefined
, false
and the numbers 0
and NaN
.
请注意,如果您专门检查数字,使用此方法会错过 0
是一个常见错误,并且首选 num !== 0
(或num !== -1
或 ~num
(也检查 -1
的黑客代码))用于返回 -1 的函数
,例如indexOf
).
Please note that if you are specifically checking for numbers, it is a common mistake to miss 0
with this method, and num !== 0
is preferred (or num !== -1
or ~num
(hacky code that also checks against -1
)) for functions that return -1
, e.g. indexOf
).
这篇关于如何在 JavaScript 中检查 null 值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何在 JavaScript 中检查 null 值?


基础教程推荐
- Karma-Jasmine:如何正确监视 Modal? 2022-01-01
- 悬停时滑动输入并停留几秒钟 2022-01-01
- 动态更新多个选择框 2022-01-01
- 我什么时候应该在导入时使用方括号 2022-01-01
- 响应更改 div 大小保持纵横比 2022-01-01
- 有没有办法使用OpenLayers更改OpenStreetMap中某些要素 2022-09-06
- 角度Apollo设置WatchQuery结果为可用变量 2022-01-01
- 在for循环中使用setTimeout 2022-01-01
- 在 JS 中获取客户端时区(不是 GMT 偏移量) 2022-01-01
- 当用户滚动离开时如何暂停 youtube 嵌入 2022-01-01