如何在JavaScript中检查空值?我写了下面的代码,但没用。

if (pass == null || cpass == null || email == null || cemail == null || user == null) {      

    alert("fill all columns");
    return false;  

}   

如何在JavaScript程序中查找错误?


当前回答

严格相等运算符:-

我们可以通过===

if ( value === null ){

}

仅通过使用if

if( value ) {

}

如果值不是:

无效的未定义NaN公司空字符串(“”)假的0

其他回答

严格相等运算符:-

我们可以通过===

if ( value === null ){

}

仅通过使用if

if( value ) {

}

如果值不是:

无效的未定义NaN公司空字符串(“”)假的0

与操作员进行可选检查怎么样?

例如:

// check mother for null or undefined and 
// then if mother exist check her children also
// this 100% sure it support and valid in JS today.
// Apart of that C# have almost the same operator using the same way
if (mother?.children) {

}
else {
 // it is null, undefined, etc...

}

JavaScript在检查“空”值方面非常灵活。我猜你实际上是在寻找空字符串,在这种情况下,这个更简单的代码会起作用:

if(!pass || !cpass || !email || !cemail || !user){

它将检查空字符串(“”)、null、undefined、false以及数字0和NaN。

请注意,如果您是专门检查数字,则使用此方法错过0是一个常见错误,num!==对于返回-1的函数(例如indexOf),首选0(或num!==-1或~num(同时检查-1的黑客代码))。

空值的简单解决方案:

function isEmpty(value) {
        return (
            value === null || value === undefined || value === '' ||
            (Array.isArray(value) && value.length === 0) ||
            (!(value instanceof Date) && typeof value === 'object' && Object.keys(value).length === 0)
        );
    }

只要在所有地方用==替换==即可。

==是一个松散或抽象的相等比较

==是严格的相等比较

有关更多详细信息,请参阅MDN关于平等比较和相同性的文章。