JavaScript中是否存在字符串.Empty,还是只是检查“”?
当前回答
试试这个
str.value.length == 0
其他回答
如果您需要确保字符串不只是一堆空格(我假设这是为了表单验证),则需要对空格进行替换。
if(str.replace(/\s/g,"") == ""){
}
我使用组合,最快的检查是第一个。
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);
}
我在这里没有找到好答案(至少没有适合我的答案)
所以我决定自己回答:
value==未定义| | value==null | | value===“”;
你需要开始检查它是否未定义。否则,您的方法可能会爆炸,然后您可以检查它是否等于null或等于空字符串。
你不能拥有!!或者仅当(value),因为如果你勾选0,它会给你一个错误的答案(0是错误的)。
话虽如此,用如下方法将其包装起来:
公共静态isEmpty(值:any):布尔值{返回值==未定义| |值==null | |值===“”;}
PS.:你不需要检查typeof,因为它甚至在进入方法之前就会爆炸并抛出
我使用:
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
同时,我们可以有一个函数来检查所有“空”,如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