JavaScript中是否存在字符串.Empty,还是只是检查“”?
当前回答
您可以验证以下方法并了解其区别。
var j=未定义;console.log((typeof j==“undefined”)?“真”:“假”);var j=空;console.log((j==null)?“真”:“假”);var j=“”;console.log((!j)?“真”:“假”);var j=“Hi”;console.log((!j)?“真”:“假”);
其他回答
Try:
if (str && str.trim().length) {
//...
}
非常通用的“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))
);
}
但是,我不建议使用它,因为您的目标变量应该是特定类型的(即字符串、数字或对象?),所以应用与该变量相关的检查。
检查var a;存在删除值中的假空格,然后测试是否为空如果((a)&&(a.trim()!=“”)){//如果变量a不为空,请执行以下操作}
var s; // undefined
var s = ""; // ""
s.length // 0
JavaScript中没有表示空字符串的内容。检查长度(如果您知道var始终是字符串)或“”
我使用组合,最快的检查是第一个。
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);
}