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


当前回答

我通常用这样的东西,

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

其他回答

我做了一些研究,如果将非字符串和非空/空值传递给测试器函数会发生什么。正如许多人所知,(0==“”)在JavaScript中是真的,但由于0是一个值,而不是空或null,因此您可能需要测试它。

以下两个函数仅对未定义的、null、空/空白值返回true,对其他所有值(如数字、布尔值、对象、表达式等)返回false。

function IsNullOrEmpty(value)
{
    return (value == null || value === "");
}
function IsNullOrWhiteSpace(value)
{
    return (value == null || !/\S/.test(value));
}

存在更复杂的示例,但这些示例很简单,并给出了一致的结果。不需要测试undefined,因为它包含在(value==null)检查中。您还可以通过如下方式将C#行为添加到String中来模拟它们:

String.IsNullOrEmpty = function (value) { ... }

您不希望将其放在Strings原型中,因为如果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; } }]
];
var s; // undefined
var s = ""; // ""
s.length // 0

JavaScript中没有表示空字符串的内容。检查长度(如果您知道var始终是字符串)或“”

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

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

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

此外,如果您认为填充空白的字符串为“空”。

可以使用以下正则表达式进行测试:

!/\S/.test(string); // Returns true if blank.

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

if (!str.length) { ...