JavaScript中是否存在字符串.Empty,还是只是检查“”?


当前回答

我使用:

function empty(e) {
  switch (e) {
    case "":
    case 0:
    case "0":
    case null:
    case false:
    case undefined:
      return true;
    default:
      return false;
  }
}

empty(null) // true
empty(0) // true
empty(7) // false
empty("") // true
empty((function() {
    return ""
})) // false

其他回答

下面是我用来处理这个问题的一些自定义函数。以及代码如何运行的示例。

常量v1=0常量v2=“4”常量v2e=未定义常量v2e2=空常量v3=[1,2,3,4]常量v3e=[]常量v4=真常量v4e=假常量v5={测试:'值'}常量v5e={}常量v6=“NotEmpty”常量v6e=“”函数为Numeric(n){回来isNaN(parseFloat(n))&&isFinite(n)}函数isEmpty(v,zeroIsEmpty=false){/***当执行类型检查时,null将始终返回“object”,因此我们首先过滤掉它*@参见https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/typeof#typeof_null*/如果(v==空){返回true}如果(v==真){return false}if(类型v==='对象'){回来对象键(v)长度}如果(isNumeric(v)){返回zeroIsEmpty?parseFloat(v)==0:false}回来v | |!v.length | | v.length<1}console.log(isEmpty(v1),isEmpty(v1,true))console.log(isEmpty(v2),isEmptyconsole.log(isEmpty(v3),isEmpty(v3e))console.log(isEmpty(v4),isEmptyconsole.log(isEmpty(v5),isEmptyconsole.log(isEmpty(v6),isEmpty(v6e))

同样作为参考,以下是Lodash isEmpty的来源:

检查是否为字符串类型,如果不为空:

const isNonEmptyString = (val) => typeof val === 'string' && !!val

忽略空白字符串,您可以使用它来检查null、空和undefined:

var obj = {};
(!!obj.str) // Returns false

obj.str = "";
(!!obj.str) // Returns false

obj.str = null;
(!!obj.str) // Returns false

它简明扼要,适用于未定义的财产,尽管它不是最可读的。

也可以使用正则表达式:

if((/^\s*$/).test(str)) { }

检查是否有空字符串或空白字符串。

非常通用的“All-In-One”功能(但不推荐):

function is_empty(x)
{
    return (                                                           //don't put newline after return
        (typeof x == 'undefined')
              ||
        (x == null)
              ||
        (x == false)        //same as: !x
              ||
        (x.length == 0)
              ||
        (x == 0)            // note this line, you might not need this. 
              ||
        (x == "")
              ||
        (x.replace(/\s/g,"") == "")
              ||
        (!/[^\s]/.test(x))
              ||
        (/^\s*$/.test(x))
    );
}

但是,我不建议使用它,因为您的目标变量应该是特定类型的(即字符串、数字或对象?),所以应用与该变量相关的检查。