JavaScript中是否存在字符串.Empty,还是只是检查“”?
当前回答
我没有注意到一个考虑到字符串中可能存在空字符的答案。例如,如果我们有一个空字符串:
var y = "\0"; // an empty string, but has a null character
(y === "") // false, testing against an empty string does not work
(y.length === 0) // false
(y) // true, this is also not expected
(y.match(/^[\s]*$/)) // false, again not wanted
要测试其空性,可以执行以下操作:
String.prototype.isNull = function(){
return Boolean(this.match(/^[\0]*$/));
}
...
"\0".isNull() // true
它在空字符串和空字符串上工作,所有字符串都可以访问它。此外,它还可以扩展为包含其他JavaScript空字符或空白字符(即非分隔空格、字节顺序标记、行/段落分隔符等)。
其他回答
我使用组合,最快的检查是第一个。
function isBlank(pString) {
if (!pString) {
return true;
}
// Checks for a non-white space character
// which I think [citation needed] is faster
// than removing all the whitespace and checking
// against an empty string
return !/[^\s]+/.test(pString);
}
检查您是否试图传递未定义的术语也是一个好主意。
function TestMe() {
if((typeof str != 'undefined') && str) {
alert(str);
}
};
TestMe();
var str = 'hello';
TestMe();
我通常遇到这样的情况:当对象实例的字符串属性不为空时,我想做一些事情。这很好,只是属性并不总是存在。
我在这里没有找到好答案(至少没有适合我的答案)
所以我决定自己回答:
value==未定义| | value==null | | value===“”;
你需要开始检查它是否未定义。否则,您的方法可能会爆炸,然后您可以检查它是否等于null或等于空字符串。
你不能拥有!!或者仅当(value),因为如果你勾选0,它会给你一个错误的答案(0是错误的)。
话虽如此,用如下方法将其包装起来:
公共静态isEmpty(值:any):布尔值{返回值==未定义| |值==null | |值===“”;}
PS.:你不需要检查typeof,因为它甚至在进入方法之前就会爆炸并抛出
我通常用这样的东西,
if (!str.length) {
// Do something
}
非常通用的“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))
);
}
但是,我不建议使用它,因为您的目标变量应该是特定类型的(即字符串、数字或对象?),所以应用与该变量相关的检查。
推荐文章
- 在React Native中使用Fetch授权头
- 为什么我的球(物体)没有缩小/消失?
- 如何使用jQuery检测页面的滚动位置
- if(key in object)或者if(object. hasownproperty (key)
- 一元加/数字(x)和parseFloat(x)之间的区别是什么?
- angularjs中的compile函数和link函数有什么区别
- 删除绑定中添加的事件监听器
- getActivity()在Fragment函数中返回null
- 很好的初学者教程socket.io?
- HtmlSpecialChars在JavaScript中等价于什么?
- React: 'Redirect'没有从' React -router-dom'中导出
- 如何在React中使用钩子强制组件重新渲染?
- 我如何使用Jest模拟JavaScript的“窗口”对象?
- 我如何等待一个承诺完成之前返回一个函数的变量?
- 在JavaScript中根据键值查找和删除数组中的对象