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


当前回答

检查var a;存在删除值中的假空格,然后测试是否为空如果((a)&&(a.trim()!=“”)){//如果变量a不为空,请执行以下操作}

其他回答

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

常量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的来源:

我使用组合,最快的检查是第一个。

function isBlank(pString) {
    if (!pString) {
        return true;
    }
    // Checks for a non-white space character
    // which I think [citation needed] is faster
    // than removing all the whitespace and checking
    // against an empty string
    return !/[^\s]+/.test(pString);
}

如果您需要确保字符串不只是一堆空格(我假设这是为了表单验证),则需要对空格进行替换。

if(str.replace(/\s/g,"") == ""){
}

最接近str.Empty(前提是str是String)的是:

if (!str.length) { ...
var x ="  ";
var patt = /^\s*$/g;
isBlank = patt.test(x);
alert(isBlank); // Is it blank or not??
x = x.replace(/\s*/g, ""); // Another way of replacing blanks with ""
if (x===""){
    alert("ya it is blank")
}