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

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

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

}   

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


当前回答

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

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

试试看,帮你找到答案

其他回答

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

例如:

// 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 safeOrZero(route) {
  try {
    Function(`return (${route})`)();
  } catch (error) {
    return 0;
  }
  return Function(`return (${route})`)();
}

路线是任何一条价值链都会爆炸。我将它用于jQuery/cacherio和对象等。

示例1:一个简单的对象,例如this const testObj={items:[{val:'haya'},{val:null},{val:'hum!'}];};。

但它可能是一个非常大的物体,我们甚至没有制造过。所以我通过了:

let value1 = testobj.items[2].val;  // "hum!"
let value2 = testobj.items[3].val;  // Uncaught TypeError: Cannot read property 'val' of undefined

let svalue1 = safeOrZero(`testobj.items[2].val`)  // "hum!"
let svalue2 = safeOrZero(`testobj.items[3].val`)  // 0

当然,如果您愿意,可以使用null或“无值”。。。任何适合您需要的。

通常,如果找不到DOM查询或jQuery选择器,可能会抛出错误。但使用类似于:

const bookLink = safeOrZero($('span.guidebook > a')[0].href);
if(bookLink){
  [...]
}

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

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 ( value === null ){

}

仅通过使用if

if( value ) {

}

如果值不是:

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