如何在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个回答

14

我使用了一种组合方式,最快速的检查先执行。

function isBlank(pString) {
    if (!pString) {
        return true;
    }
    // Checks for a non-white space character
    // which I think [citation needed] is faster
    // than removing all the whitespace and checking
    // against an empty string
    return !/[^\s]+/.test(pString);
}

3
请问您能否解释一下什么情况下需要进行长度检查?如果使用!pString,不是可以捕获任何空值/空字符串吗?这似乎可行。例如:var test=''; if (!test) alert('empty'); - Nicholi
2
我直到十年后才看到这个评论。但是没错,你说得对,我会更新的。 :) - Will
1
一步一步地结合我们十年的知识 :) - Nicholi
@Nicholi,2031年见! - Will

14

开始翻译:

return (!value || value == undefined || value == "" || value.length == 0);

看最后一个条件,如果value == "",它的长度必须为0。因此将其删除:

return (!value || value == undefined || value == "");

但是!在JavaScript中,一个空字符串是false。因此,排除值等于“”:

return (!value || value == undefined);

并且 !undefined 的值为 true,因此不需要进行这个检查。因此我们有:

return (!value);

而且我们不需要括号:

return !value

如果 value = falsevalue = 0,你会根据问题返回正确的响应吗? - nerez

13

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

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


2
有趣的分析。我认为在99.9%的情况下这并不相关。但是,最近我发现如果MySQL列包含空字符("\0"),则MySQL会将该列评估为“null”。而Oracle则不会将"\0"评估为空值,而是将其视为长度为1的字符串(其中一个字符是空字符)。如果不正确处理,这可能会导致混淆,因为许多Web开发人员确实使用后端数据库,该数据库可能会传递不同类型的“null”值。这应该牢记于每个开发人员的脑海中。 - cartbeforehorse

11

我在这里没有看到一个好的答案(至少对我来说不适合)。

所以我决定自己回答:

value === undefined || value === null || value === "";

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

你不能只用!!或者if(value),因为如果你检查0,它会给你一个假答案(0是false)。

因此,请将其包装在一个方法中,如下所示:

public static isEmpty(value: any): boolean { return value === undefined || value === null || value === ""; }

附注:你不需要检查typeof,因为它进入方法之前就会出错并抛出异常。


最好使用Boolean(value)结构,它将未定义和null值(以及0、-0、false、NaN)视为false。请参见https://dev59.com/SXRA5IYBdhLWcg3wtwSe - Zhuravlev A.

11
我对将非字符串和非空/ null值传递给测试函数的结果进行了一些研究。许多人知道,在JavaScript中(0 ==“”)为true,但由于0是一个值而不是空或null,您可能想要进行测试。
以下两个函数仅对未定义,null,空格/空值返回true,并对其他所有内容(例如数字,布尔值,对象,表达式等)返回false。
function IsNullOrEmpty(value)
{
    return (value == null || value === "");
}
function IsNullOrWhiteSpace(value)
{
    return (value == null || !/\S/.test(value));
}

存在更复杂的例子,但这些例子很简单并且给出了一致的结果。没有必要测试未定义的值,因为它已经包含在(value == null)检查中。您还可以通过像这样将它们添加到字符串来模仿C#的行为:
String.IsNullOrEmpty = function (value) { ... }

您不希望将其放入字符串原型中,因为如果String类的实例为空,则会出现错误:

String.prototype.IsNullOrEmpty = function (value) { ... }
var myvar = null;
if (1 == 2) { myvar = "OK"; } // Could be set
myvar.IsNullOrEmpty(); // Throws error

我用以下值数组进行了测试。如果你有疑问,可以循环遍历它来测试你的函数。

// Helper items
var MyClass = function (b) { this.a = "Hello World!"; this.b = b; };
MyClass.prototype.hello = function () { if (this.b == null) { alert(this.a); } else { alert(this.b); } };
var z;
var arr = [
// 0: Explanation for printing, 1: actual value
    ['undefined', undefined],
    ['(var) z', z],
    ['null', null],
    ['empty', ''],
    ['space', ' '],
    ['tab', '\t'],
    ['newline', '\n'],
    ['carriage return', '\r'],
    ['"\\r\\n"', '\r\n'],
    ['"\\n\\r"', '\n\r'],
    ['" \\t \\n "', ' \t \n '],
    ['" txt \\t test \\n"', ' txt \t test \n'],
    ['"txt"', "txt"],
    ['"undefined"', 'undefined'],
    ['"null"', 'null'],
    ['"0"', '0'],
    ['"1"', '1'],
    ['"1.5"', '1.5'],
    ['"1,5"', '1,5'], // Valid number in some locales, not in JavaScript
    ['comma', ','],
    ['dot', '.'],
    ['".5"', '.5'],
    ['0', 0],
    ['0.0', 0.0],
    ['1', 1],
    ['1.5', 1.5],
    ['NaN', NaN],
    ['/\S/', /\S/],
    ['true', true],
    ['false', false],
    ['function, returns true', function () { return true; } ],
    ['function, returns false', function () { return false; } ],
    ['function, returns null', function () { return null; } ],
    ['function, returns string', function () { return "test"; } ],
    ['function, returns undefined', function () { } ],
    ['MyClass', MyClass],
    ['new MyClass', new MyClass()],
    ['empty object', {}],
    ['non-empty object', { a: "a", match: "bogus", test: "bogus"}],
    ['object with toString: string', { a: "a", match: "bogus", test: "bogus", toString: function () { return "test"; } }],
    ['object with toString: null', { a: "a", match: "bogus", test: "bogus", toString: function () { return null; } }]
];

如果您停止使用==并使用===,则可以解决此问题if(s ===“”)。 - Scott Marcus

11

同时,我们可以编写一个函数来检查所有“空值”,例如null,undefined,'',' ',{},[]。因此我刚刚编写了这个函数。

var isEmpty = function(data) {
    if(typeof(data) === 'object'){
        if(JSON.stringify(data) === '{}' || JSON.stringify(data) === '[]'){
            return true;
        }else if(!data){
            return true;
        }
        return false;
    }else if(typeof(data) === 'string'){
        if(!data.trim()){
            return true;
        }
        return false;
    }else if(typeof(data) === 'undefined'){
        return true;
    }else{
        return false;
    }
}

使用案例和结果。

console.log(isEmpty()); // true
console.log(isEmpty(null)); // true
console.log(isEmpty('')); // true
console.log(isEmpty('  ')); // true
console.log(isEmpty(undefined)); // true
console.log(isEmpty({})); // true
console.log(isEmpty([])); // true
console.log(isEmpty(0)); // false
console.log(isEmpty('Hey')); // false

10

使用空值合并运算符修剪空格:

if (!str?.trim()) {
  // do something...
}

看起来很酷,但是 str.trim() 就足够了。在我看来,一个人永远不应该过于复杂化事情。 - Hexodus
2
对于那些可能需要它的人,我只是随便提供一下。?. 没有更简单的了。如果 str 是 nullish,.trim() 将会抛出一个错误。 - sean

10

试试这个:

export const isEmpty = string => (!string || !string.length);

10

所有这些答案都很好。

但我不能确定变量是一个字符串,是否只包含空格(对我很重要),并且可以包含'0'(字符串)。

我的版本:

function empty(str){
    return !str || !/[^\s]+/.test(str);
}

empty(null); // true
empty(0); // true
empty(7); // false
empty(""); // true
empty("0"); // false
empty("  "); // true

jsfiddle上进行的示例。


2
什么?如果你期望一个字符串,empty(0)empty(7)应该返回相同的值。 - Bennett McElwee
在我的特定情况下 - empty("0") 必须返回 false(因为它是一个非空字符串),但是 empty(0) 必须返回 true,因为它是空的 :) - Andron
但是0并不是空的!它是一个数字,数字不能是满的或空的。当然,这是您的函数,因此必须满足您的要求,但在这种情况下,“empty”是一个误导性的名称。 - Bennett McElwee
我认为“empty”这个名称很好。在 PHP 函数的文档中,empty函数返回“如果变量存在且具有非空、非零值,则返回 FALSE。否则返回 TRUE。” PHP 和此函数之间的区别在于,字符串“'0'”不会被视为空。 - Andron
就像我说的,这是你的函数:你可以随意命名。但是empty这个名称不准确且容易误导。有趣的是PHP也有一个命名不当的empty函数,但是PHP的缺陷与JavaScript无关。 - Bennett McElwee

9

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

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

类型检查是为了避免在testundefinednull时出现运行时错误。


我非常确定 test === "" 是等价的,而且更短。 - Flimm

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