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


当前回答

有很多答案,还有很多不同的可能性!

毫无疑问,快速简单的实现是赢家:if(!str.length){…}

然而,还有许多其他例子。我建议,最好的功能方法是:

函数为空(str){if(str类型==‘undefined‘||!str | | str.length==0 | | str==“”||!/[^\s]/.test(str)||/^\s*$/.test(str)|| str.replace(/\s/g,“”)==“)返回true;其他的return false;}

我知道有点过分了。

其他回答

我在这里没有找到好答案(至少没有适合我的答案)

所以我决定自己回答:

value==未定义| | value==null | | value===“”;

你需要开始检查它是否未定义。否则,您的方法可能会爆炸,然后您可以检查它是否等于null或等于空字符串。

你不能拥有!!或者仅当(value),因为如果你勾选0,它会给你一个错误的答案(0是错误的)。

话虽如此,用如下方法将其包装起来:

公共静态isEmpty(值:any):布尔值{返回值==未定义| |值==null | |值===“”;}

PS.:你不需要检查typeof,因为它甚至在进入方法之前就会爆炸并抛出

最接近str.Empty(前提是str是String)的是:

if (!str.length) { ...

没有isEmpty()方法,您必须检查类型和长度:

if (typeof test === 'string' && test.length === 0){
  ...

当测试未定义或为空时,需要进行类型检查以避免运行时错误。

检查是否为空:

var str = "Hello World!";
if(str === ''){alert("THE string str is EMPTY");}

要检查它是否为string类型,请执行以下操作:

var str = "Hello World!";
if(typeof(str) === 'string'){alert("This is a String");}

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

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空字符或空白字符(即非分隔空格、字节顺序标记、行/段落分隔符等)。