JavaScript 中是否有一个,或者只是检查 ?string.Empty
""
网友回答:
为了检查变量是否为 falsey 或它的长度属性是否等于零(对于字符串,这意味着它是空的),我使用:
function isEmpty(str) {
return (!str || str.length === 0 );
}
(请注意,字符串不是唯一具有长度属性的变量,例如,数组也具有它们
。
或者,您可以使用(不是这样)新选择的链接和箭头函数来简化:
const isEmpty = (str) => (!str?.length);
它将检查长度,在值为 null 的情况下返回,而不会引发错误。在空值的情况下,零是假的,结果仍然有效。undefined
为了检查变量是否为 falsey 或字符串是否仅包含空格或为空,我使用:
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());
请注意,猴子修补内置类型是有争议的,因为它可能会破坏依赖于内置类型现有结构的代码,无论出于何种原因。
网友回答:
要检查真实值,请执行以下操作:
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
}
网友回答:
前面所有的答案都很好,但这会更好。使用双 NOT 运算符 ():!!
if (!!str) {
// Some code here
}
或者使用类型转换:
if (Boolean(str)) {
// Code here
}
两者都执行相同的功能。将变量类型转换为布尔值,其中 是变量。str
false
null
undefined
0
000
""
false
true
"0"
" "
)模板简介:该模板名称为【JavaScript 中是否有一个,或者只是检查 ?string.Empty””】,大小是暂无信息,文档格式为.编程语言,推荐使用Sublime/Dreamweaver/HBuilder打开,作品中的图片,文字等数据均可修改,图片请在作品中选中图片替换即可,文字修改直接点击文字修改即可,您也可以新增或修改作品中的内容,该模板来自用户分享,如有侵权行为请联系网站客服处理。欢迎来懒人模板【JavaScript】栏目查找您需要的精美模板。