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

新手上路,请多包涵

JavaScript 中是否有 string.Empty ,或者只是检查 "" 的情况?

原文由 casademora 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 935
2 个回答

空字符串,未定义,null,…

要检查 真实值

 if (strValue) {
 // strValue was non-empty string, true, 42, Infinity, [], ...
 }

检查 虚假值

 if (!strValue) {
 // strValue was empty string, false, 0, null, undefined, ...
 }


空字符串(仅限!)

要检查是否完全为空字符串,请使用 === 运算符"" 进行严格相等比较:

 if (strValue === "") {
 // strValue was empty string
 }

要严格检查不是空字符串,请使用 !== 运算符

 if (strValue !== "") {
 // strValue was not an empty string
 }

原文由 bdukes 发布,翻译遵循 CC BY-SA 4.0 许可协议

为了检查一个变量是否为 或者它的长度属性是否为零(对于字符串,这意味着它是空的),我使用:

 function isEmpty(str) {
    return (!str || str.length === 0 );
}

(请注意,字符串并不是唯一具有 length 属性的变量,例如,数组也有它们。)

或者,您可以使用(不是这样)新的可选链接和箭头函数来简化:

 const isEmpty = (str) => (!str?.length);

它将检查长度,返回 undefined 如果是空值,不会抛出错误。在空值的情况下,零是假的,结果仍然有效。

为了检查变量是否为假或字符串是否仅包含空格或为空,我使用:

 function isBlank(str) {
    return (!str || /^\s*$/.test(str));
}

如果你愿意,你可以像这样 猴子修补 String 原型:

 String.prototype.isEmpty = function() {
    // This doesn't work the same way as the isEmpty function used
    // in the first example, it will return true for strings containing only whitespace
    return (this.length === 0 || !this.trim());
};
console.log("example".isEmpty());

请注意,猴子修补内置类型是有争议的,因为无论出于何种原因,它都可能破坏依赖于内置类型现有结构的代码。

原文由 Jano González 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题