如何在JavaScript中检查空/未定义/空字符串?

3976
在 JavaScript 中是否有类似于 string.Empty 的方法,或者只需要检查 "" 是否为空?

5
仅供参考,我认为String类最有用的API在Mozillajavascript kit上。elated.com提供了关于String所有属性、方法的教程...请注意:Mozilla链接已更新为https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/String。 - Gene T
2
如果需求明确指定,那将会非常有帮助。isEmpty 应该在什么情况下返回 true?检查 "" 暗示它只应在值为字符串类型且长度为 0 时返回 true。这里的许多答案都假设它也应该对某些或所有 falsy 值返回 true。 - RobG
str.length > -1 - Omar bakhsh
我完全同意@RobG的观点,这个问题定义得很糟糕。你为什么会认为nullundefined是空的呢?一个空字符串就是一个空字符串,它不是nullundefined - Flimm
@GeneT的链接已经失效,这里提供Mozilla参考文档的更新链接:https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/String - randy
显示剩余2条评论
54个回答

8

忽略空格字符串,您可以使用此方法检查是否为null、空或未定义:

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

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

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

这种方法简洁并且适用于未定义的属性,尽管它不是最易读的。


你在这里检查真实性,这比仅仅检查空字符串、undefinednull要复杂一些。 - Flimm

7
您可以轻松地将其添加到 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

!(!!this.length) 而不是只做 !this(或者对于第二个选项,做 !this.trim())有什么好处?长度为零的字符串已经是虚假的了,括号是多余的,并且三次否定它与一次否定它完全相同。 - John Montgomery
1
请不要污染原型。 - sean
通常认为像这样使用猴子补丁是不好的实践。 - Flimm

7

我通常会使用类似于以下的方法:

if (str == "") {
     //Do Something
}
else {
     //Do Something Else
}

4
== 运算符不是严格比较的。因此,如果 str == "",则 str 可能是 nullundefinedfalse0[] 等等。 - alexandre-rousseau

7

试试这个

str.value.length == 0

6
"".value.length会导致错误。正确写法为str.length === 0。请注意,翻译过程中不得添加解释或其他内容。 - AndFisher
2
如果str等于undefinednull,则会抛出TypeError - alexandre-rousseau

6
不要假设你检查的变量是一个字符串。不要假设如果此变量有长度,则它是一个字符串。
事实上,仔细考虑您的应用程序必须执行和可以接受的内容。构建一个强大的东西。
如果您的方法/函数只能处理非空字符串,则测试参数是否为非空字符串,而不要使用一些“技巧”。
以下是一个在这里不小心遵循某些建议将会导致错误的示例。
var getLastChar = function (str) { if (str.length > 0) return str.charAt(str.length - 1) }
getLastChar('hello') => "o"
getLastChar([0,1,2,3]) => TypeError: Object [object Array] has no method 'charAt'
因此,我建议使用
if (myVar === '') ...

这个答案应该被置顶。 - Flimm

5
你可以使用 typeof 运算符和 length 方法来检查这个。
const isNonEmptyString = (value) => typeof(value) == 'string' && value.length > 0

5

试试这段代码:

function isEmpty(strValue)
{
    // Test whether strValue is empty
    if (!strValue || strValue.trim() === "" ||
        (strValue.trim()).length === 0) {
        // Do something
    }
}

3
在条件结尾处使用(strValue.trim()).length === 0)的目的是什么?这不是和strValue.trim() === ""重复了吗? - pys

5

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

    let undefinedStr;
    if (!undefinedStr) {
      console.log("String is undefined");
    }
    
    let emptyStr = "";
    if (!emptyStr) {
      console.log("String is empty");
    }
    
    let nullStr = null;
    if (!nullStr) {
      console.log("String is null");
    }


第一个条件适用于任何假值,而不仅仅是 undefined。此答案未检查类型。 - Flimm

5
您可以通过以下方式进行验证并了解差异。

var j = undefined;
console.log((typeof j == 'undefined') ? "true":"false");
var j = null; 
console.log((j == null) ? "true":"false");
var j = "";
console.log((!j) ? "true":"false");
var j = "Hi";
console.log((!j) ? "true":"false");


5

检查它是否为字符串类型且不为空:

const isNonEmptyString = (val) => typeof val === 'string' && !!val

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接