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
其他回答
Try:
if (str && str.trim().length) {
//...
}
检查var a;存在删除值中的假空格,然后测试是否为空如果((a)&&(a.trim()!=“”)){//如果变量a不为空,请执行以下操作}
有很多答案,还有很多不同的可能性!
毫无疑问,快速简单的实现是赢家: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;}
我知道有点过分了。
非常通用的“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))
);
}
但是,我不建议使用它,因为您的目标变量应该是特定类型的(即字符串、数字或对象?),所以应用与该变量相关的检查。
您可以使用lodash:_.isEmpty(值)。
它涵盖了许多情况,如{}、“”、null、undefined等。
但对于JavaScript原始数据类型的Number类型(如_.isEmpty(10)或_.isEmpty(Number.MAX_VALUE)),它总是返回true。