JavaScript中是否存在字符串.Empty,还是只是检查“”?
当前回答
您可以很容易地将它添加到JavaScript中的原生String对象中,并反复使用它。。。如果您想检查“”空字符串,下面的代码可以为您完成这项工作:
String.prototype.isEmpty = String.prototype.isEmpty || function() {
return !(!!this.length);
}
否则,如果您想同时检查“”空字符串和“”带空格,可以通过添加trim()来完成,类似于下面的代码:
String.prototype.isEmpty = String.prototype.isEmpty || function() {
return !(!!this.trim().length);
}
你可以这样称呼它:
''.isEmpty(); //return true
'alireza'.isEmpty(); //return false
其他回答
我在这里没有找到好答案(至少没有适合我的答案)
所以我决定自己回答:
value==未定义| | value==null | | value===“”;
你需要开始检查它是否未定义。否则,您的方法可能会爆炸,然后您可以检查它是否等于null或等于空字符串。
你不能拥有!!或者仅当(value),因为如果你勾选0,它会给你一个错误的答案(0是错误的)。
话虽如此,用如下方法将其包装起来:
公共静态isEmpty(值:any):布尔值{返回值==未定义| |值==null | |值===“”;}
PS.:你不需要检查typeof,因为它甚至在进入方法之前就会爆炸并抛出
开始于:
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
Try:
if (str && str.trim().length) {
//...
}
您可以使用typeof运算符和length方法检查这一点。
const isNonEmptyString = (value) => typeof(value) == 'string' && value.length > 0
这是一个错误的值。
第一种解决方案:
const str = "";
return str || "Hello"
第二种解决方案:
const str = "";
return (!!str) || "Hello"; // !!str is Boolean
第三种解决方案:
const str = "";
return (+str) || "Hello"; // !!str is Boolean