【问题标题】:How to check if a value is not null and not empty string in JS如何检查JS中的值是否不为null且不是空字符串
【发布时间】:2021-05-08 21:00:02
【问题描述】:

在Javascript中是否有任何检查值是否不为空且不是空字符串?我正在使用以下一个:

var data; //get its value from db 
if(data != null && data != '') {
   // do something
}

但我想知道是否还有其他更好的解决方案。谢谢。

【问题讨论】:

  • if(data) 就足够了,正如它所说的 here
  • 我试过了,但在这两种情况之一中它不起作用。
  • 谢谢大家,我会试试这个。我希望它会起作用。
  • undefined 是一种特殊情况,根据您的逻辑,应该触发 // do something 但不会。

标签: javascript


【解决方案1】:

如果你真的想确认一个变量不是 null 并且不是一个空字符串,你可以这样写:

if(data !== null && data !== '') {
   // do something
}

请注意,我更改了您的代码以检查类型是否相等 (!==|===)。

但是,如果您只是想确保代码仅针对“合理”值运行,那么您可以像其他人已经说过的那样编写:

if (data) {
  // do something
}

因为在 javascript 中,null 值和空字符串都等于 false(即null == false)。

这两部分代码之间的区别在于,对于第一部分,每个不是特别为 null 或空字符串的值都将输入if。但是,在第二个中,每个真实值都将输入 iffalse0nullundefined 和空字符串,不会。

【讨论】:

  • 0 在很多情况下是一个合理的值
  • 这就是为什么合理这个词用引号括起来的原因:)
  • @Adam 如果没有,您可以将其留空并使用 else。这总是会按预期反转。
  • 这不应该是数据吗!== null || data !== '' 而不是使用 && ?
  • @Imdad OP 要求检查值是否不为空且不是空字符串,所以不。
【解决方案2】:

而不是使用

if(data !== null && data !== ''  && data!==undefined) {

// do something
}

你可以使用下面的简单代码

if(Boolean(value)){ 
// do something 
}
  • 直观上为“空”的值(如 0、空字符串、null、未定义和 NaN)变为 false
  • 其他值变为真

【讨论】:

  • 我喜欢这个解决方案,因为它最干净。
【解决方案3】:

null 和空字符串在 JS 中都是假值。因此,

if (data) { ... }

完全够用了。

不过,请注意:我会避免在我的代码中包含可能以不同类型表现的变量。如果数据最终将是一个字符串,那么我最初会用一个空字符串定义我的变量,所以你可以这样做:

if (data !== '') { ... }

没有 null(或任何奇怪的东西,如 data = "0")妨碍。

【讨论】:

    【解决方案4】:
    if (data?.trim().length > 0) {
       //use data
    }
    

    如果数据为 nullishnullundefined),?. optional chaining operator 将短路并返回 undefined,这将在 if 表达式中计算为 false。

    【讨论】:

    • 老实说我不知道​​这个运营商..不幸的是一些Android浏览器不支持它,但其他支持都很好!
    【解决方案5】:

    我经常测试真实值以及字符串中的空格:

    if(!(!data || data.trim().length === 0)) {
      // do something here
    }
    

    如果您有一个包含一个或多个空格的字符串,它将评估为真。

    【讨论】:

      【解决方案6】:

      检查字符串是否为undefinednull""的简单解决方案:-

      const value = null;
      if(!value) {
        console.log('value is either null, undefined or empty string');
      }
      

      【讨论】:

        【解决方案7】:

        null 和 empty 都可以按如下方式进行验证:

        <script>
        function getName(){
            var myname = document.getElementById("Name").value;
            if(myname != '' && myname != null){
                alert("My name is "+myname);
            }else{
                alert("Please Enter Your Name");
            }       
        }
        

        【讨论】:

          【解决方案8】:

          试试---------

          function myFun(){
          var inputVal=document.getElementById("inputId").value;
          if(inputVal){
          document.getElementById("result").innerHTML="<span style='color:green'>The value is "+inputVal+'</span>';
          }
          else{
          document.getElementById("result").innerHTML="<span style='color:red'>Something error happen! the input May be empty.</span>";
          }
          }
          <input type="text" id="inputId">
          <input type="button" onclick="myFun()" value="View Result">
          <h1 id="result"></h1>

          【讨论】:

            【解决方案9】:

            我厌倦了专门检查空字符串和空字符串,现在我通常只编写并调用一个小函数来为我完成。

            /**
             * Test if the given value equals null or the empty string.
             * 
             * @param {string} value
            **/
            const isEmpty = (value) => value === null || value === '';
            
            // Test:
            isEmpty('');        // true
            isEmpty(null);      // true
            isEmpty(1);         // false
            isEmpty(0);         // false
            isEmpty(undefined); // false
            

            【讨论】:

              【解决方案10】:

              当我们的代码本质上为空时,在特定情况下可能意味着以下任何一种情况;

              • 0 表示数值
              • 0.0 作为浮点值
              • 字符串值中的'0'
              • '0.0' 作为字符串值
              • null 与 Null 值一样,它也可能捕获 undefined,也可能不会捕获
              • 未定义为未定义值
              • false 为 false 真实值,根据机会 0 也为真实值,但如果我们想捕获 false 的原样怎么办
              • '' 没有空格或制表符的空字符串值
              • ' ' 字符串,只有空格或制表符

              在现实生活中,正如 OP 所说,我们可能希望全部测试它们,或者有时我们可能只想测试有限的一组条件。

              通常if(!a){return true;} 在大多数情况下都能发挥作用,但它不会涵盖更广泛的条件。

              另一个成功的黑客是return (!value || value == undefined || value == "" || value.length == 0);

              但是如果我们需要控制整个过程呢?

              在原生核心 JavaScript 中没有简单的鞭打解决方案,它必须被采用。考虑到我们放弃了对旧版 IE11 的支持(老实说,即使是 Windows,我们也应该如此)低于所有现代浏览器中因受挫而诞生的解决方案;

               function empty (a,b=[])
               {if(!Array.isArray(b)) return; 
               var conditions=[null,'0','0.0',false,undefined,''].filter(x => !b.includes(x));
               if(conditions.includes(a)|| (typeof a === 'string' && conditions.includes(a.toString().trim())))
               {return true;};
               return false;};`
              

              解决方案背后的逻辑是函数有两个参数ab,a是我们需要检查的值,b是我们需要排除的具有设定条件的数组上面列出的预定义条件。 b 的默认值设置为空数组 []。

              函数的第一次运行是检查b是否为数组,如果不是则提前退出函数。

              下一步是计算 [null,'0','0.0',false,undefined,''] 和数组 b 的数组差异。如果 b 是空数组,则预定义条件将成立,否则它将删除匹配值。

              条件 = [预定义集] - [待排除集] filter 函数正是利用它。 现在我们在数组集合中有条件,我们需要做的就是检查值是否在条件数组中。 includes 函数正是这样做的,无需自己编写讨厌的循环,让 JS 引擎完成繁重的工作。

              问题 如果我们要将 a 转换为字符串进行比较,那么 0 和 0.0 可以正常运行,但是 Null 和 Undefined 会通过错误阻塞整个脚本。我们需要边缘案例解决方案。如果第一个条件不满足,下面简单的 || 涵盖了边缘情况。如果未满足,则通过 include 运行另一个早期检查会提前退出。

              if(conditions.includes(a)||  (['string', 'number'].includes(typeof a) && conditions.includes(a.toString().trim())))
              

              trim() 函数将覆盖更广泛的空白和仅制表符的值,并且只会在极端情况下发挥作用。

              游乐场

              function empty (a,b=[]){
              if(!Array.isArray(b)) return;
              conditions=[null,'0','0.0',false,undefined,''].filter(x => !b.includes(x));
              if(conditions.includes(a)|| 
              (['string', 'number'].includes(typeof a) && conditions.includes(a.toString().trim()))){
               return true;
              } 
              return false;
              }
              
              console.log('1 '+empty());
              console.log('2 '+empty(''));
              console.log('3 '+empty('      '));
              console.log('4 '+empty(0));
              console.log('5 '+empty('0'));
              console.log('6 '+empty(0.0));
              console.log('7 '+empty('0.0'));
              console.log('8 '+empty(false));
              console.log('9 '+empty(null));
              console.log('10 '+empty(null,[null]));
              console.log('11 dont check 0 as number '+empty(0,['0']));
              console.log('12 dont check 0 as string '+empty('0',['0']));
              console.log('13 as number for false as value'+empty(false,[false]));

              让我们让它变得复杂——如果我们要比较的值是数组它的自身,并且可以嵌套得尽可能深。如果我们要检查数组中的任何值是否为空怎么办,这可能是一个边缘业务案例。

              function empty (a,b=[]){
                  if(!Array.isArray(b)) return;
              
                  conditions=[null,'0','0.0',false,undefined,''].filter(x => !b.includes(x));
                  if(Array.isArray(a) && a.length > 0){
                  for (i = 0; i < a.length; i++) { if (empty(a[i],b))return true;} 
                  } 
                  
                  if(conditions.includes(a)|| 
                  (['string', 'number'].includes(typeof a) && conditions.includes(a.toString().trim()))){
                   return true;
                  } 
                  return false;
                  }
              
              console.log('checking for all values '+empty([1,[0]]));
              console.log('excluding for 0 from condition '+empty([1,[0]], ['0']));

              我在我的框架中采用的简单且更广泛的用例功能;

              • 控制在给定情况下空的确切定义是什么
              • 允许重新定义空的条件
              • 几乎可以比较字符串、数字、浮点数、truthy、null、未定义和深度数组中的所有内容
              • 在制定解决方案时要牢记可重复性和灵活性。如果要处理简单的一两个案例,所有其他答案都适用。但是,总是存在这样的情况,即在 sn-ps 上进行编码时定义的空更改在这种情况下可以完美地工作。

              【讨论】:

                【解决方案11】:

                function validateAttrs(arg1, arg2, arg3,arg4){
                    var args = Object.values(arguments);
                    return (args.filter(x=> x===null || !x)).length<=0
                }
                console.log(validateAttrs('1',2, 3, 4));
                console.log(validateAttrs('1',2, 3, null));
                console.log(validateAttrs('1',undefined, 3, 4));
                console.log(validateAttrs('1',2, '', 4));
                console.log(validateAttrs('1',2, 3, null));

                【讨论】:

                  猜你喜欢
                  • 2011-04-05
                  • 2019-01-25
                  • 1970-01-01
                  • 1970-01-01
                  • 1970-01-01
                  • 2011-11-25
                  • 2012-03-23
                  相关资源
                  最近更新 更多