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


当前回答

Undercore.js JavaScript库,http://underscorejs.org/,提供了一个非常有用的_.isEmpty()函数,用于检查空字符串和其他空对象。

参考:http://underscorejs.org/#isEmpty

isEmpty _.isEmpty(对象)如果可枚举对象不包含值(无可枚举的所有者属性),则返回true。对于字符串和类似数组的对象_.isEmpty检查长度属性是否为0。_.is空([1,2,3]);=>假_.isEmpty({});=>真

其他非常有用的Undercore.js函数包括:

http://underscorejs.org/#isNull_.isNull(对象)http://underscorejs.org/#isUndefined_.is未定义(值)http://underscorejs.org/#has_.有(对象,键)

其他回答

试试这个

str.value.length == 0

isBlank函数的最终和最短变体:

/***将返回:*False for:对于所有带字符的字符串*True for:false,null,undefined,0,0.0,“”,“”。**@param字符串*@return{boolean}*/函数isBlank(str){return(!!!str||/^\s*$/.test(str));}//测试console.log(“isBlank TRUE变量:”);console.log(isBlank(false));console.log(isBlank(未定义));console.log(isBlank(null));console.log(isBlank(0));console.log(isBlank(0.0));console.log(isBlank(“”));console.log(isBlank(“”));console.log(“isBlank FALSE变量:”);console.log(isBlank(“0”));console.log(isBlank(“0.0”));console.log(isBlank(“0”));console.log(isBlank(“0”));console.log(isBlank(“测试字符串”));console.log(isBlank(“true”));console.log(isBlank(“false”));console.log(isBlank(“null”));console.log(isBlank(“未定义”));

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

试试看:

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

为了检查变量是否为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修补内置类型是有争议的,因为无论出于什么原因,它都会破坏依赖于内置类型现有结构的代码。