如何在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程序中查找错误?
当前回答
首先,您有一个没有函数体的return语句。这很可能会引发错误。
一个更干净的检查方法是简单地使用!操作员:
if (!pass || !cpass || !email || !cemail || !user) {
alert("fill all columns");
}
其他回答
首先,您有一个没有函数体的return语句。这很可能会引发错误。
一个更干净的检查方法是简单地使用!操作员:
if (!pass || !cpass || !email || !cemail || !user) {
alert("fill all columns");
}
与操作员进行可选检查怎么样?
例如:
// 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中的undefined和null,只需编写以下内容:
if (!var) {
console.log("var IS null or undefined");
} else {
console.log("var is NOT null or undefined");
}
只要在所有地方用==替换==即可。
==是一个松散或抽象的相等比较
==是严格的相等比较
有关更多详细信息,请参阅MDN关于平等比较和相同性的文章。
你可以使用try-catch finally
try {
document.getElementById("mydiv").innerHTML = 'Success' //assuming "mydiv" is undefined
} catch (e) {
if (e.name.toString() == "TypeError") //evals to true in this case
//do something
} finally {}
您也可以抛出自己的错误。看看这个。