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

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

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

}   

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


当前回答

检查错误条件:

// Typical API response data
let data = {
  status: true,
  user: [],
  total: 0,
  activity: {sports: 1}
}

// A flag that checks whether all conditions were met or not
var passed = true;

// Boolean check
if (data['status'] === undefined || data['status'] == false){
  console.log("Undefined / no `status` data");
  passed = false;
}

// Array/dict check
if (data['user'] === undefined || !data['user'].length){
  console.log("Undefined / no `user` data");
  passed = false;
}

// Checking a key in a dictionary
if (data['activity'] === undefined || data['activity']['time'] === undefined){
   console.log("Undefined / no `time` data");
   passed = false;
}

// Other values check
if (data['total'] === undefined || !data['total']){
  console.log("Undefined / no `total` data");
  passed = false;
}

// Passed all tests?
if (passed){
  console.log("Passed all tests");
}

其他回答

首先,您有一个没有函数体的return语句。这很可能会引发错误。

一个更干净的检查方法是简单地使用!操作员:

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

    alert("fill all columns");

}

我找到了另一种方法来测试该值是否为空:

if(variable >= 0 && typeof variable === "object")

null同时充当数字和对象。比较null>=0或null<=0结果为true。比较null==0或null>0或null<0将导致false。但由于null也是一个对象,我们可以将其检测为null。

我做了一个更复杂的函数性质,它比typeof做得更好,并且可以被告知要包含或保持分组的类型

/*函数性质of(变量,[包含类型])包括的类型有null-null将导致“未定义”,如果包含,则将导致“null”NaN-NaN将导致“未定义”,或如果包含,将导致“NaN”-infinity-将负-无穷与“无限”分开number-将数字拆分为“int”或“double”array-将“array”与“object”分开空-空的“字符串”将导致“空”或空=未定义-空“字符串”将导致“未定义”*/函数性质of(v,…类型){/*null*/if(v===null)返回类型。includes('null')?“null”:“未定义”;/*NaN*/if(typeof v==“number”)返回(isNaN(v))?类型。包括('NaN')?“NaN”:“未定义”:/*-无穷大*/(v+1===v)?(types.includes('-infinity')&&v==Number.NEGATIVE_infinity)?“-无限”:“无限”:/*number*/(types.includes('number'))?(数字.isInteger(v))?“int”:“double”:“number”;/*array*/if(typeof v==“object”)return(types.includes('array')&&array.isArray(v))?“array”:“object”;/*空*/if(typeof v==“string”)返回(v==”)?types.includes(“空”)?“空”:/*空=未定义*/types.includes('empty=未定义')?“undefined”:“string”:“字符串”;否则返回v的类型}//演示let types=[null,“”,“string”,undefined,NaN,Infinity,-Invinity,false,“false”,true,“true”,0,1,-1,0.1,“test”,{var:1},[1,2],{0:1,1:2,长度:2}]for(i在类型中){console.log(“natureof”,类型[i],“=”,natureof(类型[i]”,“null”,“NaN”,“-ninfinity”,“number”,“array”,“empty=undefined”))}

这是一个非常非人的代码。但有效:

if((pass, cpass, email, cemail, user !== null)){

试试看,帮你找到答案

严格相等运算符:-

我们可以通过===

if ( value === null ){

}

仅通过使用if

if( value ) {

}

如果值不是:

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

您可以使用lodash模块检查值是否为空或未定义

_.isNil(value)
Example 

 country= "Abc"
    _.isNil(country)
    //false

   state= null
    _.isNil(state)
    //true

city= undefined
    _.isNil(state)
    //true

   pin= true
    _.isNil(pin)
    // false   

参考链接:https://lodash.com/docs/#isNil