JavaScript中是否存在字符串.Empty,还是只是检查“”?
当前回答
忽略空白字符串,您可以使用它来检查null、空和undefined:
var obj = {};
(!!obj.str) // Returns false
obj.str = "";
(!!obj.str) // Returns false
obj.str = null;
(!!obj.str) // Returns false
它简明扼要,适用于未定义的财产,尽管它不是最可读的。
其他回答
非常通用的“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))
);
}
但是,我不建议使用它,因为您的目标变量应该是特定类型的(即字符串、数字或对象?),所以应用与该变量相关的检查。
为了检查变量是否为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修补内置类型是有争议的,因为无论出于什么原因,它都会破坏依赖于内置类型现有结构的代码。
试试这个
str.value.length == 0
function tell()
{
var pass = document.getElementById('pasword').value;
var plen = pass.length;
// Now you can check if your string is empty as like
if(plen==0)
{
alert('empty');
}
else
{
alert('you entered something');
}
}
<input type='text' id='pasword' />
这也是检查字段是否为空的通用方法。
最接近str.Empty(前提是str是String)的是:
if (!str.length) { ...
推荐文章
- 我如何使用Jest模拟JavaScript的“窗口”对象?
- 我如何等待一个承诺完成之前返回一个函数的变量?
- 在JavaScript中根据键值查找和删除数组中的对象
- 使嵌套JavaScript对象平放/不平放的最快方法
- 如何以及为什么'a'['toUpperCase']()在JavaScript工作?
- 有Grunt生成index.html不同的设置
- 文档之间的区别。addEventListener和window。addEventListener?
- 如何检查动态附加的事件监听器是否存在?
- 如何写setTimeout与参数Coffeescript
- 将JavaScript字符串中的多个空格替换为单个空格
- JavaScript: override alert()
- 重置setTimeout
- 如何确保<select>表单字段被禁用时提交?
- jQuery有不聚焦的方法吗?
- 反应钩子-正确的方式清除超时和间隔