JavaScript中是否存在字符串.Empty,还是只是检查“”?
当前回答
嗯,检查这个的最简单的函数是。。。
const checkEmpty=string=>(strim.trim()==“”)||!strim.trim();
用法:
checkEmpty(""); // returns true.
checkEmpty("mystr"); // returns false.
就是这么简单。:)
其他回答
我通常使用以下内容:
if (str == "") {
//Do Something
}
else {
//Do Something Else
}
嗯,检查这个的最简单的函数是。。。
const checkEmpty=string=>(strim.trim()==“”)||!strim.trim();
用法:
checkEmpty(""); // returns true.
checkEmpty("mystr"); // returns false.
就是这么简单。:)
没有isEmpty()方法,您必须检查类型和长度:
if (typeof test === 'string' && test.length === 0){
...
当测试未定义或为空时,需要进行类型检查以避免运行时错误。
Undercore.js JavaScript库,http://underscorejs.org/,提供了一个非常有用的_.isEmpty()函数,用于检查空字符串和其他空对象。
参考:http://underscorejs.org/#isEmpty
isEmpty _.isEmpty(对象)如果可枚举对象不包含值(无可枚举的所有者属性),则返回true。对于字符串和类似数组的对象_.isEmpty检查长度属性是否为0。_.is空([1,2,3]);=>假_.isEmpty({});=>真
其他非常有用的Undercore.js函数包括:
http://underscorejs.org/#isNull_.isNull(对象)http://underscorejs.org/#isUndefined_.is未定义(值)http://underscorejs.org/#has_.有(对象,键)
您可以很容易地将它添加到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