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


当前回答

也可以使用正则表达式:

if((/^\s*$/).test(str)) { }

检查是否有空字符串或空白字符串。

其他回答

我使用:

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

我通常用这样的东西,

if (!str.length) {
    // Do something
}

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

if (!str.length) { ...

忽略空白字符串,您可以使用它来检查null、空和undefined:

var obj = {};
(!!obj.str) // Returns false

obj.str = "";
(!!obj.str) // Returns false

obj.str = null;
(!!obj.str) // Returns false

它简明扼要,适用于未定义的财产,尽管它不是最可读的。

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

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

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