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


当前回答

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

if (!str.length) { ...

其他回答

我使用:

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

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

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

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

毫无疑问,快速简单的实现是赢家: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;}

我知道有点过分了。

您可以很容易地将它添加到JavaScript中的原生String对象中,并反复使用它。。。如果您想检查“”空字符串,下面的代码可以为您完成这项工作:

String.prototype.isEmpty = String.prototype.isEmpty || function() {
  return !(!!this.length);
}

否则,如果您想同时检查“”空字符串和“”带空格,可以通过添加trim()来完成,类似于下面的代码:

String.prototype.isEmpty = String.prototype.isEmpty || function() {
   return !(!!this.trim().length);
}

你可以这样称呼它:

''.isEmpty(); //return true
'alireza'.isEmpty(); //return false

前面的所有答案都很好,但这会更好。使用双NOT运算符(!!):

if (!!str) {
    // Some code here
}

或使用类型铸造:

if (Boolean(str)) {
    // Code here
}

两者的功能相同。将变量类型转换为Boolean,其中str是一个变量。

对于null、undefined、0000、“”、false,它返回false。对于除空字符串之外的所有字符串值(包括“0”和“”等字符串),它都返回true