JavaScript中是否存在字符串.Empty,还是只是检查“”?
当前回答
非常通用的“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))
);
}
但是,我不建议使用它,因为您的目标变量应该是特定类型的(即字符串、数字或对象?),所以应用与该变量相关的检查。
其他回答
空字符串,未定义,null。。。
检查真实值:
if (strValue) {
// strValue was non-empty string, true, 42, Infinity, [], ...
}
要检查错误值,请执行以下操作:
if (!strValue) {
// strValue was empty string, false, 0, null, undefined, ...
}
空字符串(仅限!)
要检查是否正好为空字符串,请使用==运算符与“”进行严格相等比较:
if (strValue === "") {
// strValue was empty string
}
要严格检查非空字符串,请使用!==操作员:
if (strValue !== "") {
// strValue was not an empty string
}
我使用组合,最快的检查是第一个。
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);
}
检查您是否试图传递未定义的术语也是一个好主意。
function TestMe() {
if((typeof str != 'undefined') && str) {
alert(str);
}
};
TestMe();
var str = 'hello';
TestMe();
我通常遇到这样的情况:当对象实例的字符串属性不为空时,我想做一些事情。这很好,只是属性并不总是存在。
同时,我们可以有一个函数来检查所有“空”,如null、undefined、“”、“”,{}、[]。所以我写了这个。
var isEmpty = function(data) {
if(typeof(data) === 'object'){
if(JSON.stringify(data) === '{}' || JSON.stringify(data) === '[]'){
return true;
}else if(!data){
return true;
}
return false;
}else if(typeof(data) === 'string'){
if(!data.trim()){
return true;
}
return false;
}else if(typeof(data) === 'undefined'){
return true;
}else{
return false;
}
}
用例和结果。
console.log(isEmpty()); // true
console.log(isEmpty(null)); // true
console.log(isEmpty('')); // true
console.log(isEmpty(' ')); // true
console.log(isEmpty(undefined)); // true
console.log(isEmpty({})); // true
console.log(isEmpty([])); // true
console.log(isEmpty(0)); // false
console.log(isEmpty('Hey')); // false
另一种方式,但我相信bdukes的答案是最好的。
var myString = 'hello';
if(myString.charAt(0)){
alert('no empty');
}
alert('empty');