JavaScript中是否存在字符串.Empty,还是只是检查“”?


当前回答

我不会太担心最有效的方法。使用最明确的意图。对我来说,这通常是strVar==“”。

根据Constantin的评论,如果strVar可以包含一个0整数值,那么这确实是一种意图明确的情况。

其他回答

您也应该经常检查类型,因为JavaScript是一种鸭子类型的语言,所以您可能不知道数据在过程中何时以及如何更改。因此,以下是更好的解决方案:

let undefinedStr;if(!undefinedStr){console.log(“字符串未定义”);}let emptyStr=“”;if(!emptyStr){console.log(“字符串为空”);}让nullStr=null;if(!nullStr){console.log(“字符串为空”);}

同时,我们可以有一个函数来检查所有“空”,如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

开始于:

return (!value || value == undefined || value == "" || value.length == 0);

查看最后一个条件,如果值==“”,则其长度必须为0。因此,删除它:

return (!value || value == undefined || value == "");

但是等等!在JavaScript中,空字符串为false。因此,下降值==“”:

return (!value || value == undefined);

和undefined为true,因此不需要检查。因此,我们有:

return (!value);

我们不需要括号:

return !value
var s; // undefined
var s = ""; // ""
s.length // 0

JavaScript中没有表示空字符串的内容。检查长度(如果您知道var始终是字符串)或“”

我没有注意到一个考虑到字符串中可能存在空字符的答案。例如,如果我们有一个空字符串:

var y = "\0"; // an empty string, but has a null character
(y === "") // false, testing against an empty string does not work
(y.length === 0) // false
(y) // true, this is also not expected
(y.match(/^[\s]*$/)) // false, again not wanted

要测试其空性,可以执行以下操作:

String.prototype.isNull = function(){ 
  return Boolean(this.match(/^[\0]*$/)); 
}
...
"\0".isNull() // true

它在空字符串和空字符串上工作,所有字符串都可以访问它。此外,它还可以扩展为包含其他JavaScript空字符或空白字符(即非分隔空格、字节顺序标记、行/段落分隔符等)。