如何在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((pass, cpass, email, cemail, user !== null)){
试试看,帮你找到答案
其他回答
这是一个非常非人的代码。但有效:
if((pass, cpass, email, cemail, user !== null)){
试试看,帮你找到答案
这是对WebWander关于检查NaN的解决方案的评论(我还没有足够的代表留下正式评论)。解决方案如下
if(!parseInt(variable) && variable != 0 && typeof variable === "number")
但对于将舍入为0的有理数(例如变量=0.1),这将失败。更好的测试是:
if(isNaN(variable) && typeof variable === "number")
“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
我做了一个非常简单的功能,效果很好:
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){
[...]
}
您可以检查某些值是否为空,如下所示
[pass,cpass,email,cemail,user].some(x=> x===null)
let pass=1;设cpass=2;让电子邮件=3;let cemail=空;让用户=5;如果([pass,cpass,email,cemail,user].some(x=>x==null)){警报(“填充所有列”);//return false;}
奖金:为什么==比==更清楚(来源)
a==b
a===b