如何解决如何在 JavaScript 中检查空/未定义/空字符串?
如果你只是想检查是否有真值,你可以这样做:
if (strValue) {
//do something
}
如果您需要专门检查空字符串而不是空字符串,我认为检查""
是您最好的选择,使用运算符(===
这样您就知道它实际上是您要比较的字符串)。
if (strValue === "") {
//...
}
为了检查变量是否为假或者它的长度属性是否等于零(对于字符串来说,这意味着它是空的),我使用:
function isEmpty(str) {
return (!str || str.length === 0 );
}
(请注意,字符串不是唯一具有length
属性的变量,例如,数组也有它们。)
为了检查变量是否为假或字符串是否仅包含空格或为空,我使用:
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());
解决方法
JavaScript中是否有一个简单的string.Empty可用,或者它只是一个检查的情况”“?