如何在 JavaScript 中检查 null 值? [英] How do I check for null values in JavaScript?

查看:38
本文介绍了如何在 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){

它将检查空字符串 ("")、nullundefinedfalse 和数字 0NaN.

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 值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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