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


当前回答

也可以使用正则表达式:

if((/^\s*$/).test(str)) { }

检查是否有空字符串或空白字符串。

其他回答

我在这里没有找到好答案(至少没有适合我的答案)

所以我决定自己回答:

value==未定义| | value==null | | value===“”;

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

你不能拥有!!或者仅当(value),因为如果你勾选0,它会给你一个错误的答案(0是错误的)。

话虽如此,用如下方法将其包装起来:

公共静态isEmpty(值:any):布尔值{返回值==未定义| |值==null | |值===“”;}

PS.:你不需要检查typeof,因为它甚至在进入方法之前就会爆炸并抛出

也可以使用正则表达式:

if((/^\s*$/).test(str)) { }

检查是否有空字符串或空白字符串。

空字符串,未定义,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修补内置类型是有争议的,因为无论出于什么原因,它都会破坏依赖于内置类型现有结构的代码。

试试看:

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