如何在JavaScript中检查空值?我写了下面的代码,但没用。
if (pass == null || cpass == null || email == null || cemail == null || user == null) {
alert("fill all columns");
return false;
}
如何在JavaScript程序中查找错误?
如何在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
其他回答
“Object.is()”方法可用于确定两个值是否相同。因此,您可以使用它来检查对象是否为空。
检查空值
let testA = null; //null
console.log(Object.is(testA, null)); //true //null === null
if(Object.is(testA, null)) {
console.log("This is a Null Value");
}
Output:
true
This is a Null Value
检查未定义的值
let testB; //undefined
console.log(Object.is(testB, undefined)); //true //undefined === undefined
if(Object.is(testB, undefined)) {
console.log("This is an undefined Value");
}
Output:
true
This is an undefined Value
如果要同时检查undefined和null,请使用此选项。
let testC; //undefined
console.log(Object.is(testC, undefined)); //true //undefined === undefined
console.log(Object.is(testC, null)); //false //undefined === null
if (Object.is(testC, undefined) || Object.is(testC, null)){
console.log("The value is either undefined or null");
}
if (!(Object.is(testC, undefined) || Object.is(testC, null))){
console.log("The value is neither undefined nor null");
}
Output:
true
false
The value is either undefined or null
看看他们:https://onecompiler.com/javascript/3ymdqd34v
Mozilla解释:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is
与操作员进行可选检查怎么样?
例如:
// 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...
}
试试看:
if (!variable && typeof variable === "object") {
// variable is null
}
这是对WebWander关于检查NaN的解决方案的评论(我还没有足够的代表留下正式评论)。解决方案如下
if(!parseInt(variable) && variable != 0 && typeof variable === "number")
但对于将舍入为0的有理数(例如变量=0.1),这将失败。更好的测试是:
if(isNaN(variable) && typeof variable === "number")
在JavaScript中,没有字符串等于null。
当pass为空字符串时,您可能希望pass==null为真,因为您知道松散的相等运算符==执行某些类型的强制。
例如,此表达式为true:
'' == 0
相反,严格相等运算符==表示这是错误的:
'' === 0
假定“”和0大致相等,您可以合理地推测“”和null大致相等。然而,事实并非如此。
此表达式为false:
'' == null
将任何字符串与null进行比较的结果为false。因此,pass==null和所有其他测试始终为false,用户永远不会收到警报。
要修复代码,请将每个值与空字符串进行比较:
pass === ''
如果您确定pass是一个字符串,pass==“”也会起作用,因为只有空字符串与空字符串大致相等。另一方面,一些专家表示,在JavaScript中始终使用严格相等是一种好的做法,除非您特别想执行松散相等运算符执行的类型强制。
如果您想知道哪些值对大致相等,请参阅Mozilla文章中关于此主题的“Sameness比较”表。