如何在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程序中查找错误?
当前回答
这是对WebWander关于检查NaN的解决方案的评论(我还没有足够的代表留下正式评论)。解决方案如下
if(!parseInt(variable) && variable != 0 && typeof variable === "number")
但对于将舍入为0的有理数(例如变量=0.1),这将失败。更好的测试是:
if(isNaN(variable) && typeof variable === "number")
其他回答
你可以使用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 {}
您也可以抛出自己的错误。看看这个。
只要在所有地方用==替换==即可。
==是一个松散或抽象的相等比较
==是严格的相等比较
有关更多详细信息,请参阅MDN关于平等比较和相同性的文章。
您可以使用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
我做了一个非常简单的功能,效果很好:
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){
[...]
}
首先,您有一个没有函数体的return语句。这很可能会引发错误。
一个更干净的检查方法是简单地使用!操作员:
if (!pass || !cpass || !email || !cemail || !user) {
alert("fill all columns");
}