【问题标题】:How do I check for null values in JavaScript?如何在 JavaScript 中检查 null 值?
【发布时间】:2011-08-25 14:56:56
【问题描述】:

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

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

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

}   

我如何在我的 JavaScript 程序中发现错误?

【问题讨论】:

  • 您确定您正在测试的值实际上是 null 而不仅仅是空字符串吗?
  • 在js中测试null应该使用严格的操作符===
  • @davin - 是的,但不是这里的问题,因为如果是这样,该语句仍然有效。
  • @cwolves,如果我认为这是问题所在,我会将该评论作为答案。看看我的措辞,我显然是在参考 OP 的实践对语言做出一般性陈述,而不是提议这可以解决他的问题。
  • @TRiG 提议的更改从根本上改变了问题的性质,以至于答案(不仅仅是我的)失去了上下文并且没有意义。编辑应该只是评论。

标签: javascript null compare comparison equality


【解决方案1】:

使用操作员进行可选检查怎么样?

例如:

// 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...

}

【讨论】:

    【解决方案2】:

    JavaScript 在检查“null”值方面非常灵活。我猜你实际上是在寻找空字符串,在这种情况下,这个更简单的代码会起作用:

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

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

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

    【讨论】:

    • 了解该测试的哪些部分对应哪些值会非常有用。有时您会特别寻找一个。
    • 有点迟到的声明,但是是的,您可以对每个 @inorganik 进行测试,请参阅下面的答案
    • 读者,在对数值数据使用这种类型的测试时请小心。不要使用!!! 来测试典型数字数据上的nullundefined,除非您还想丢弃0 值。
    • 答案本身说明了这一点:“......和数字0......”。我相信这个答案非常适合给定上下文(我推断是“用户名、密码、电子邮件”)的问题,他们没有检查 0 值。然而,鉴于这个问题和答案的受欢迎程度,我同意在答案本身中值得一提。
    • @Hendeca - 翻白眼去阅读实际问题中的代码。 很明显询问用户名和密码。我不是在猜测什么,我只是出于礼貌。我回答了他们需要而不是他们所问的这一事实让您感到困扰,这很荒谬。就是这样,大多数时候人们不知道他们应该要求什么。在原始问题的上下文中,这个答案是正确的。现在停止添加噪音。
    【解决方案3】:

    乍一看,这似乎是覆盖率和严格性之间的简单权衡

    • == 涵盖多个值,可以用更少的代码处理更多的场景。
    • === 是最严格的,这使得它可以预测。

    可预测性总是胜出,这似乎使 === 成为一种万能的解决方案。

    但这是错误。尽管=== 是可预测的,但它并不总是会产生可预测的代码,因为它忽略了场景。

    const options = { };
    if (options.callback !== null) {
      options.callback();      // error --> callback is undefined.
    }
    

    一般而言== 对空值检查做了更可预测的工作:

    • 一般来说,nullundefined 都表示同一个意思:“有东西不见了”。为了可预测性,您需要检查这两个值。然后== null 做得很好,因为它正好涵盖了这两个值。 (== null 等价于=== null && === undefined

    • 在特殊情况下,您确实希望在nullundefined 之间有一个明确的区别。在这些情况下,您最好使用严格的=== undefined=== null(例如,缺失/忽略/跳过和空/清除/删除之间的区别。)但它很少见

    这不仅很少见,而且是要避免的。您不能将undefined 存储在传统数据库中。由于互操作性的原因,您也不应该在 API 设计中依赖 undefined 值。但即使你完全不区分,你也不能假设undefined 不会发生。 我们周围的人都间接地采取了概括null/undefined 的行动(这就是为什么像 this 这样的问题被关闭为“有意见的”。)。

    所以,回到你的问题。使用== null 没有任何问题。它做的正是它应该做的。

    // FIX 1 --> yes === is very explicit
    const options = { };
    if (options.callback !== null && 
        options.callback !== undefined) {
      options.callback();
    }
    
    
    // FIX 2 --> but == covers both
    const options = { };
    if (options.callback != null) {
      options.callback();
    }
    
    // FIX 3 --> optional chaining also covers both.
    const options = { };
    options.callback?.();
    

    【讨论】:

      【解决方案4】:

      其实我觉得你可能需要使用 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'' 值。所以我使用了第二个测试,但您可能也需要过滤它们,这可能会导致您使用第一个测试。

      【讨论】:

      • value !== null || value !== undefined 始终为真。我想你的意思是value !== null && value !== undefined。这实际上与 value != null 相同(准确检查 null 和 undefined。)
      • @bvdb 抱歉,在代码中我使用了正确的表达式,但我忘记了:-D 我已修复它,谢谢。
      【解决方案5】:

      您可以如下检查某个值是否为空

      [pass,cpass,email,cemail,user].some(x=> x===null) 
      

      let pass=1;
      let cpass=2;
      let email=3;
      let cemail=null;
      let user=5;
      
      if ( [pass,cpass,email,cemail,user].some(x=> x===null) ) {     
          alert("fill all columns");
          //return false;  
      }   

      奖励:为什么 ===== (source) 更清楚

      a == b

      a === b

      【讨论】:

      • 伟大的 2 个图表,我冒昧地将它们合并:docs.google.com/drawings/d/…
      • 除了上面的2个图表。虽然if ([] == false) 为真(如图所示),但if ([]) 的计算结果也为真。
      • 喜欢这些图表。 (JavaScript wordle?)
      【解决方案6】:

      要检查 null 具体,您可以使用:

      if (variable === null)
      

      此测试会通过 null,而不会通过 ""undefinedfalse0NaN

      此外,我为每个“类假”值提供了绝对检查(对于!variable 将返回真值)。

      注意,对于某些绝对检查,您需要实现使用absolutely equals: ===typeof

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

      这是每次检查的输出:

      Null Test:
      
      if (variable === null)
      
      - 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 === '')
      
      - 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 (typeof variable == "undefined")
      
      -- or --
      
      if (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)
      
      - 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)
      
      - 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 (typeof variable == 'number' && !parseFloat(variable) && variable !== 0)
      
      -- or --
      
      if (isNaN(variable))
      
      - 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 有点困难;

      【讨论】:

      • 如果使用===严格相等,类型检查的目的是什么?谢谢。此外,对于 NaN 测试,您可以使用 isNaN(value),仅当变量等于 NaN 时才会返回 true
      • 是否存在variable === null 不是“对象”类型的情况?如果没有,为什么不将检查简化为variable === null,去掉第二个连词?谢谢。
      • @HunanRostomyan 好问题,老实说,不,我认为没有。使用我刚刚测试过的here in this JSFiddlevariable === null 很可能足够安全。我还使用 ` && typeof variable === 'object'` 的原因不仅是为了说明 null 值是一个 typeof object 的有趣事实,而且也是为了跟上其他检查的流程。但是,是的,总而言之,您可以安全地使用 variable === null
      • jsfiddle.net/neoaptt/avt1cgem/1 这是分解成函数的答案。不是很有用,但我还是做了。
      • 我要做的事情几乎从来都不是一个好主意:更改此答案中的代码。具体来说,在检查 null 时,删除对类型对象完全不必要的测试。这是一个基本代码sn-p:让即使是一个初学者误会他们需要做那种冗长的事情也不是一个好主意测试。
      【解决方案7】:

      检查错误情况:

      // Typical API response data
      let data = {
        status: true,
        user: [],
        total: 0,
        activity: {sports: 1}
      }
      
      // A flag that checks whether all conditions were met or not
      var passed = true;
      
      // Boolean check
      if (data['status'] === undefined || data['status'] == false){
        console.log("Undefined / no `status` data");
        passed = false;
      }
      
      // Array/dict check
      if (data['user'] === undefined || !data['user'].length){
        console.log("Undefined / no `user` data");
        passed = false;
      }
      
      // Checking a key in a dictionary
      if (data['activity'] === undefined || data['activity']['time'] === undefined){
         console.log("Undefined / no `time` data");
         passed = false;
      }
      
      // Other values check
      if (data['total'] === undefined || !data['total']){
        console.log("Undefined / no `total` data");
        passed = false;
      }
      
      // Passed all tests?
      if (passed){
        console.log("Passed all tests");
      }
      

      【讨论】:

        【解决方案8】:

        JAVASCRIPT 中的 AFAIK 当一个变量被声明但没有赋值时,它的类型是undefined。所以我们可以检查变量,即使它是一个 object 持有一些 instance 代替 value

        创建一个帮助方法来检查返回 true 的空值并在您的 API 中使用它。

        检查变量是否为空的辅助函数:

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

        try-catch 异常 API 调用:

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

        一些测试用例:

        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));
        

        【讨论】:

        • 什么?这个答案与这篇文章无关。您是否不小心在此线程上发布了此答案?
        • 这个isEmpty 函数的行为与! 完全相同。无需发明功能。只需执行if (!pass || !cpass || !email ...)。 (已在接受的答案中显示。)根据 WebWanderer 的评论,这篇文章的中间部分“try-catch exception API call”似乎与这个问题无关。请解释您的意图 - 什么时候有用?这与问题有何关系?
        【解决方案9】:

        您可以使用 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

        【讨论】:

          【解决方案10】:

          我做了这个非常简单的功能,效果很好:

          function safeOrZero(route) {
            try {
              Function(`return (${route})`)();
            } catch (error) {
              return 0;
            }
            return Function(`return (${route})`)();
          }
          

          路线是可以爆炸的任何价值链。我将它用于 jQuery/cheerio 和对象等。

          示例 1:一个简单的对象,例如 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'No value'... 任何适合您的需求。

          如果找不到,通常 DOM 查询或 jQuery 选择器可能会抛出错误。但是使用类似的东西:

          const bookLink = safeOrZero($('span.guidebook > a')[0].href);
          if(bookLink){
            [...]
          }
          

          【讨论】:

            【解决方案11】:

            我找到了另一种方法来测试该值是否为空:

            if(variable >= 0 && typeof variable === "object")
            

            null 同时充当numberobject。比较 null >= 0null <= 0 的结果是 true。比较 null === 0null > 0null < 0 将导致错误。但由于null 也是一个对象,我们可以将其检测为空。

            我制作了一个更复杂的函数 natureof 女巫会比 typeof 做得更好,并且可以告诉我要包含或保持分组的类型

            /* function natureof(variable, [included types])
            included types are 
                null - null will result in "undefined" or if included, will result in "null"
                NaN - NaN will result in "undefined" or if included, will result in "NaN"
                -infinity - will separate negative -Inifity from "Infinity"
                number - will split number into "int" or "double"
                array - will separate "array" from "object"
                empty - empty "string" will result in "empty" or
                empty=undefined - empty "string" will result in "undefined"
            */
            function natureof(v, ...types){
            /*null*/            if(v === null) return types.includes('null') ? "null" : "undefined";
            /*NaN*/             if(typeof v == "number") return (isNaN(v)) ? types.includes('NaN') ? "NaN" : "undefined" : 
            /*-infinity*/       (v+1 === v) ? (types.includes('-infinity') && v === Number.NEGATIVE_INFINITY) ? "-infinity" : "infinity" : 
            /*number*/          (types.includes('number')) ? (Number.isInteger(v)) ? "int" : "double" : "number";
            /*array*/           if(typeof v == "object") return (types.includes('array') && Array.isArray(v)) ? "array" : "object";
            /*empty*/           if(typeof v == "string") return (v == "") ? types.includes('empty') ? "empty" : 
            /*empty=undefined*/ types.includes('empty=undefined') ? "undefined" : "string" : "string";
                                else return typeof v
            }
            
            // DEMO
            let types = [null, "", "string", undefined, NaN, Infinity, -Infinity, false, "false", true, "true", 0, 1, -1, 0.1, "test", {var:1}, [1,2], {0: 1, 1: 2, length: 2}]
            
            for(i in types){
            console.log("natureof ", types[i], " = ", natureof(types[i], "null", "NaN", "-infinity", "number", "array", "empty=undefined")) 
            }

            【讨论】:

              【解决方案12】:

              通过显式检查 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");
              }

              【讨论】:

                【解决方案13】:

                严格相等运算符:-

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

                if ( value === null ){
                
                }
                

                只需使用if

                if( value ) {
                
                }
                

                如果值不是,将评估为真:

                • 未定义
                • NaN
                • 空字符串(“”)
                • 0

                【讨论】:

                  【解决方案14】:

                  只需将所有位置的== 替换为===

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

                  === 是严格相等比较

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

                  【讨论】:

                  • 这仅在您认为undefined 不是null 时有效。否则会导致很多意想不到的行为。通常,如果您对 null/undefined 都感兴趣,但不感兴趣,则使用 ==(您应该这样做的少数情况之一)。
                  • @AndrewMao undefined 不是 null: stackoverflow.com/a/5076962/753237
                  • 我相信这就是@AndrewMao 所说的,真的。他的第一句话可能会被改写为“这只适用于 undefined 和 null 不是实际等价物的情况。”
                  • @BobRodes 感谢您澄清我糟糕的写作,我很感激 :)
                  • @AndrewMao 不客气。我个人不会说你的写作很差。我会说这比平均水平要好很多。 :)
                  【解决方案15】:

                  如果布尔值来自数据库,这将不起作用 例如:

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

                  【讨论】:

                    【解决方案16】:

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

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

                    【讨论】:

                    • !var 对于 0、""、NaN 和 false 也是 true。
                    【解决方案17】:

                    试试这个:

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

                    【讨论】:

                    • null 只是“虚假”的东西,typeof 返回“object”。
                    • 这比if (variable === null) 好多少?去年也有人提供了这个答案:stackoverflow.com/a/27550756/218196
                    【解决方案18】:

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

                    pass 为空字符串时,您可能希望pass == null 为真,因为您知道松散相等运算符== 执行某些类型的类型强制。

                    例如,这个表达式为真:

                    '' == 0
                    

                    相比之下,严格相等运算符=== 说这是错误的:

                    '' === 0
                    

                    鉴于''0 大致相等,您可以合理地推测''null 大致相等。但是,它们不是。

                    这个表达式是假的:

                    '' == null
                    

                    任何字符串与null 比较的结果都是假的。因此,pass == null 和所有其他测试总是错误的,用户永远不会收到警报。

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

                    pass === ''
                    

                    如果您确定pass 是一个字符串,pass == '' 也可以工作,因为只有空字符串松散地等于空字符串。另一方面,一些专家表示,在 JavaScript 中始终使用严格相等是一种很好的做法,除非您特别想执行松散相等运算符执行的类型强制。

                    如果您想知道哪些值对大致相等,请参阅Mozilla article on this topic 中的“相同性比较”表。

                    【讨论】:

                      【解决方案19】:

                      这是对 WebWanderer 关于检查 NaN 的解决方案的评论(我还没有足够的代表来发表正式评论)。解决方案读作

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

                      但这对于四舍五入为0 的有理数会失败,例如variable = 0.1。更好的测试是:

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

                      【讨论】:

                      • 感谢您指出错误 Gabriel,我已将修复程序放入我的答案中。除此之外,我可以通过将parseInt 更改为parseFloat 来修复测试(这对我来说首先应该是显而易见的)。我避免使用isNan 函数,因为我觉得许多开发人员将诸如isNaN 之类的函数视为某种“魔法盒子”,值进入并从中出来,我想再测试一下深入。但是,是的,您建议的测试将起作用并且完全可以使用。抱歉,直到现在我才注意到你的帖子。
                      • 太好了,这似乎有效。感谢您对为什么避免isNaN 的评论,我可以理解这个逻辑。还有 Underscore.js 方法,它看起来更加混乱/黑盒,但无论如何值得注意,因为它利用了NaN !== NaNObject.prototype.toString.call(variable) === '[object Number]' && variable !== +variable
                      【解决方案20】:

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

                      进行检查的一种更简洁的方法是简单地使用 !运营商:

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

                      【讨论】:

                      • 该代码可能在函数中,他只是没有显示它;)
                      【解决方案21】:

                      你可以使用 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 {}   
                      

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

                      【讨论】:

                      • 我认为这符合“偏执”代码。如果您真的写了这样的东西,那将是“mydiv”不可能不存在的理解。除非我们确信是这种情况,否则我们不应该使用此代码,并且我们有很多途径,例如响应代码,以确保我们在尝试这样的行之前有信心。
                      • 不要使用 try 和 catch 进行控制流。这不是一个好的解决方案。
                      猜你喜欢
                      • 2010-09-27
                      • 2022-09-23
                      • 1970-01-01
                      • 1970-01-01
                      • 1970-01-01
                      • 1970-01-01
                      • 1970-01-01
                      • 1970-01-01
                      相关资源
                      最近更新 更多