首页 文章

如何在JavaScript中检查空值?

提问于
浏览
436

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

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

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

}

我怎样才能在JavaScript程序中找到错误?

14 回答

  • 282

    要在javascript中检查 undefinednull ,您只需要编写以下代码:

    if (!var) {
            console.log("var IS null or undefined");
    } else {
            console.log("var is NOT null or undefined");
    }
    
  • 4

    关于检查“null”值,Javascript非常灵活 . 我猜你实际上在寻找空字符串,在这种情况下,这个更简单的代码将起作用:

    if(!pass || !cpass || !email || !cemail || !user){
    

    这将检查空字符串( "" ), nullundefinedfalse 以及数字 0NaN

    请注意,如果您专门检查数字,使用此方法错过 0 是一个常见的错误,并且 num !== 0 是首选(或者 num !== -1~num (对于 -1 也检查的hacky代码))对于返回 -1 的函数,例如 indexOf

  • -1

    要检查null SPECIFICALLY ,您可以使用:

    if(variable === null && typeof variable === "object")
    

    ......或者更简单:

    if(variable === null)
    

    此测试将 ONLY 传递 null ,并且不会传递 ""undefinedfalse0NaN .

    其余部分是对inorganik的评论的回应,是的,你可以单独检查每一个 .

    您需要实现 absolutely equals: ===typeof 的使用才能完全确定您的支票 .

    I've created a JSFiddle here to show all of the individual tests working

    以下是测试的所有输出:

    Null Test:
    
    if(variable === null && typeof variable === "object")
    
    - variable = ""; (false) typeof variable = string
    
    - variable = null; (true) typeof variable = object
    
    - variable = undefined; (false) typeof variable = undefined
    
    - variable = false; (false) typeof variable = boolean
    
    - variable = 0; (false) typeof variable = number
    
    - variable = NaN; (false) typeof variable = number
    
    
    
    Empty String Test:
    
    if(variable === "" && typeof variable === "string")
    
    - variable = ""; (true) typeof variable = string
    
    - variable = null; (false) typeof variable = object
    
    - variable = undefined; (false) typeof variable = undefined
    
    - variable = false; (false) typeof variable = boolean
    
    - variable = 0; (false) typeof variable = number
    
    - variable = NaN; (false) typeof variable = number
    
    
    
    
    Undefined Test:
    
    if(variable === undefined && typeof variable === "undefined")
    
    - variable = ""; (false) typeof variable = string
    
    - variable = null; (false) typeof variable = object
    
    - variable = undefined; (true) typeof variable = undefined
    
    - variable = false; (false) typeof variable = boolean
    
    - variable = 0; (false) typeof variable = number
    
    - variable = NaN; (false) typeof variable = number
    
    
    
    False Test:
    
    if(variable === false && typeof variable === "boolean")
    
    - variable = ""; (false) typeof variable = string
    
    - variable = null; (false) typeof variable = object
    
    - variable = undefined; (false) typeof variable = undefined
    
    - variable = false; (true) typeof variable = boolean
    
    - variable = 0; (false) typeof variable = number
    
    - variable = NaN; (false) typeof variable = number
    
    
    
    Zero Test:
    
    if(variable === 0 && typeof variable === "number")
    
    - variable = ""; (false) typeof variable = string
    
    - variable = null; (false) typeof variable = object
    
    - variable = undefined; (false) typeof variable = undefined
    
    - variable = false; (false) typeof variable = boolean
    
    - variable = 0; (true) typeof variable = number
    
    - variable = NaN; (false) typeof variable = number
    
    
    
    NaN Test:
    
    if(!parseFloat(variable) && variable != 0 && typeof variable === "number")
    
    - variable = ""; (false) typeof variable = string
    
    - variable = null; (false) typeof variable = object
    
    - variable = undefined; (false) typeof variable = undefined
    
    - variable = false; (false) typeof variable = boolean
    
    - variable = 0; (false) typeof variable = number
    
    - variable = NaN; (true) typeof variable = number
    

    如您所见,对于 NaN 进行测试有点困难;

  • 5

    只需在所有地方用 === 替换 == .

    == 是一个松散或抽象的平等比较

    === 是严格的平等比较

    有关更多详细信息,请参阅Equality comparisons and sameness上的MDN文章 .

  • 4

    Strict equality operator:-

    我们可以通过 === 检查null

    if ( value === null ){
    
    }
    

    只需使用 if

    if( value ) {
    
    }
    

    如果 value is not 将评估为true:

    • null

    • undefined

    • NaN

    • 空字符串(“”)

    • 0

  • 0

    首先,你有一个没有函数体的return语句 . 有可能会引发错误 .

    更清洁的检查方法是简单地使用!运营商:

    if (!pass || !cpass || !email || !cemail || !user) {
    
        alert("fill all columns");
    
    }
    
  • 23

    通过显式检查 null 但使用简化语法来改进已接受的答案:

    if ([pass, cpass, email, cemail, user].every(x=>x!==null)) {
        // your code here ...
    }
    
    // Test
    let pass=1, cpass=1, email=1, cemail=1, user=1; // just to test
    
    if ([pass, cpass, email, cemail, user].every(x=>x!==null)) {
        // your code here ...
        console.log ("Yayy! None of them are null");
    } else {
        console.log ("Oops! At-lease one of them is null");
    }
    
  • 5

    你最后可以使用try catch

    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 {}
    

    你也可以 throw 你自己的错误 . 见this .

  • 0

    这是对WebWanderer关于检查NaN的解决方案的评论(我还没有足够的代表留下正式评论) . 解决方案如下

    if(!parseInt(variable) && variable != 0 && typeof variable === "number")
    

    但是对于理性数字来说,这将会失败,而这些数字会转向 0 ,例如 variable = 0.1 . 更好的测试是:

    if(isNaN(variable) && typeof variable === "number")
    
  • 3

    在JavaScript中,没有字符串等于 null .

    pass 是一个空字符串时,你可能希望 pass == null 为真,因为你知道松散的等式运算符 == 执行某种类型的强制 .

    例如,这个表达式是真的:

    '' == 0
    

    相反,严格相等运算符 === 表示这是错误的:

    '' === 0
    

    鉴于 ''0 松散地相等,你可以合理地推测 ''null 是松散相等的 . 但是,他们不是 .

    这个表达式是假的:

    '' == null
    

    将任何字符串与 null 进行比较的结果为false . 因此, pass == null 和所有其他测试始终为false,并且用户永远不会收到警报 .

    要修复代码,请将每个值与空字符串进行比较:

    pass === ''
    

    如果你确定 pass 是一个字符串, pass == '' 也会起作用,因为只有一个空字符串松散地等于空字符串 . 另一方面,一些专家说,总是在JavaScript中使用严格相等是一个好习惯,除非你特别想要做松散相等运算符执行的类型强制 .

    如果您想知道哪些值对松散相等,请参阅Mozilla article on this topic中的表"Sameness comparisons" .

  • 3

    对于来自DB的布尔值,这不适用于ex:

    value = false
    
     if(!value) {
       // it will change all false values to not available
       return "not available"
     }
    
  • 594

    实际上我认为您可能需要使用 if (value !== null || value !== undefined) ,因为如果您使用 if (value) ,您也可以过滤0或false值 .

    考虑这两个功能:

    const firstTest = value => {
        if (value) {
            console.log('passed');
        } else {
            console.log('failed');
        }
    }
    const secondTest = value => {
        if (value !== null && value !== undefined) {
            console.log('passed');
        } else {
            console.log('failed');
        }
    }
    
    firstTest(0);            // result: failed
    secondTest(0);           // result: passed
    
    firstTest(false);        // result: failed
    secondTest(false);       // result: passed
    
    firstTest('');           // result: failed
    secondTest('');          // result: passed
    
    firstTest(null);         // result: failed
    secondTest(null);        // result: failed
    
    firstTest(undefined);    // result: failed
    secondTest(undefined);   // result: failed
    

    在我的情况下,我只需要检查值是否为null且未定义,我不想过滤 0false'' 值 . 所以我使用了第二次测试,但你可能也需要过滤它们,这可能会导致你使用第一次测试 .

  • 55

    试试这个:

    if (!variable && typeof variable === "object") {
        // variable is null
    }
    
  • -1

    请在downvote之前仔细查看 .

    JAVASCRIPT 中的AFAIK当变量为 declared 但未赋值时,其类型为 undefined . 所以我们可以检查变量,即使它是 object 持有一些 instance 代替 value .

    创建一个帮助方法来检查返回 true 的null,并在API中使用它 .

    helper function to check if variable is empty:

    function isEmpty(item){
        if(item){
            return false;
        }else{
            return true;
        }
    }
    

    try-catch exceptional API call:

    try {
    
        var pass, cpass, email, cemail, user; // only declared but contains nothing.
    
        // parametrs checking
        if(isEmpty(pass) || isEmpty(cpass) || isEmpty(email) || isEmpty(cemail) || isEmpty(user)){
            console.log("One or More of these parameter contains no vlaue. [pass] and-or [cpass] and-or [email] and-or [cemail] and-or [user]");
        }else{
            // do stuff
        }
    
    } catch (e) {
        if (e instanceof ReferenceError) {
            console.log(e.message); // debugging purpose
            return true;
        } else {
            console.log(e.message); // debugging purpose
            return true;
        }
    }
    

    some test cases:

    var item = ""; // isEmpty? true
    var item = " "; // isEmpty? false
    var item; // isEmpty? true
    var item = 0; // isEmpty? true
    var item = 1; // isEmpty? false
    var item = "AAAAA"; // isEmpty? false
    var item = NaN; // isEmpty? true
    var item = null; // isEmpty? true
    var item = undefined; // isEmpty? true
    
    console.log("isEmpty? "+isEmpty(item));
    

相关问题