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


当前回答

开始于:

return (!value || value == undefined || value == "" || value.length == 0);

查看最后一个条件,如果值==“”,则其长度必须为0。因此,删除它:

return (!value || value == undefined || value == "");

但是等等!在JavaScript中,空字符串为false。因此,下降值==“”:

return (!value || value == undefined);

和undefined为true,因此不需要检查。因此,我们有:

return (!value);

我们不需要括号:

return !value

其他回答

试试这个

str.value.length == 0

检查是否为空:

var str = "Hello World!";
if(str === ''){alert("THE string str is EMPTY");}

要检查它是否为string类型,请执行以下操作:

var str = "Hello World!";
if(typeof(str) === 'string'){alert("This is a String");}

有很多答案,还有很多不同的可能性!

毫无疑问,快速简单的实现是赢家:if(!str.length){…}

然而,还有许多其他例子。我建议,最好的功能方法是:

函数为空(str){if(str类型==‘undefined‘||!str | | str.length==0 | | str==“”||!/[^\s]/.test(str)||/^\s*$/.test(str)|| str.replace(/\s/g,“”)==“)返回true;其他的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的来源:

试试看:

export const isEmpty = string => (!string || !string.length);