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


当前回答

您可以很容易地将它添加到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

其他回答

我不会太担心最有效的方法。使用最明确的意图。对我来说,这通常是strVar==“”。

根据Constantin的评论,如果strVar可以包含一个0整数值,那么这确实是一种意图明确的情况。

非常通用的“All-In-One”功能(但不推荐):

function is_empty(x)
{
    return (                                                           //don't put newline after return
        (typeof x == 'undefined')
              ||
        (x == null)
              ||
        (x == false)        //same as: !x
              ||
        (x.length == 0)
              ||
        (x == 0)            // note this line, you might not need this. 
              ||
        (x == "")
              ||
        (x.replace(/\s/g,"") == "")
              ||
        (!/[^\s]/.test(x))
              ||
        (/^\s*$/.test(x))
    );
}

但是,我不建议使用它,因为您的目标变量应该是特定类型的(即字符串、数字或对象?),所以应用与该变量相关的检查。

空字符串,未定义,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
}

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

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

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

或者,您可以使用(并非如此)新可选的链接和箭头函数来简化:

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

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

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

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());

请注意,monkey修补内置类型是有争议的,因为无论出于什么原因,它都会破坏依赖于内置类型现有结构的代码。

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

let undefinedStr;if(!undefinedStr){console.log(“字符串未定义”);}let emptyStr=“”;if(!emptyStr){console.log(“字符串为空”);}让nullStr=null;if(!nullStr){console.log(“字符串为空”);}